kaizen-agent 1.83.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.
@@ -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" });
@@ -464,11 +465,21 @@ function browser(el: HTMLElement) {
464
465
  (el as any).browseTo = (u: string) => go(u);
465
466
  // On a phone over the tailnet, localhost is the phone itself: framing it shows nothing useful.
466
467
  const local = (u) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(u);
467
- const frame = document.createElement("iframe");
468
+ // In the desktop app the page is a <webview> in its own persistent session (desktop/src/browser-pane.ts):
469
+ // a first-party page with its own cookies, as in Orca. An iframe on the board's 127.0.0.1 origin made
470
+ // localhost:8000 third-party, so its Lax session cookie never came back (a login answered 419), and the
471
+ // framing blocks screen capture. Browsers, and an older app without the flag, keep the iframe.
472
+ const web = !!(window as any).kaizenDesktop?.browserPane;
473
+ const frame = document.createElement(web ? "webview" : "iframe") as HTMLIFrameElement;
468
474
  frame.className = "rframe";
469
475
  frame.title = "Browser";
470
- // Dev apps run; a framed page cannot navigate the board itself (no allow-top-navigation).
471
- frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads");
476
+ if (web) frame.setAttribute("allowpopups", "");
477
+ else {
478
+ // Dev apps run; a framed page cannot navigate the board itself (no allow-top-navigation).
479
+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads");
480
+ // Without these the browser blocks microphone, camera and screen capture for the framed page.
481
+ frame.setAttribute("allow", "display-capture; microphone; camera; clipboard-read; clipboard-write; fullscreen");
482
+ }
472
483
  const note = document.createElement("p");
473
484
  note.className = "rnote";
474
485
  const far = "This page is on the computer running kaizen; from this device localhost is the device itself. Use Open in browser on that computer.";
@@ -511,7 +522,7 @@ function browser(el: HTMLElement) {
511
522
  void ann.open(u).then((via) => {
512
523
  if (seq !== nav) return;
513
524
  frame.src = via ?? u;
514
- if (via) return;
525
+ if (via || web) return; // a webview is a top-level page: nothing refuses to be framed
515
526
  frameCheck(u);
516
527
  });
517
528
  };
@@ -562,6 +573,20 @@ function browser(el: HTMLElement) {
562
573
  else if (b === "back" && back.length) fwd.push(url), go(back.pop()!, false);
563
574
  else if (b === "fwd" && fwd.length) back.push(url), go(fwd.pop()!, false);
564
575
  };
576
+ if (web) {
577
+ // The page navigated on its own (a link, a form, a redirect after login): show its address.
578
+ // Through the annotator's proxy the page reports its address itself (onLocation).
579
+ const nav2 = (e: any) => {
580
+ if (e.isMainFrame === false || ann.proxied() || !/^https?:\/\//.test(e.url) || e.url === url) return;
581
+ back.push(url), (fwd.length = 0);
582
+ url = e.url;
583
+ inp.value = url;
584
+ if (ext) ext.href = url;
585
+ try { localStorage.setItem(k, url); } catch {}
586
+ };
587
+ frame.addEventListener("did-navigate", nav2);
588
+ frame.addEventListener("did-navigate-in-page", nav2);
589
+ }
565
590
  go(url, false);
566
591
  }
567
592
 
@@ -1006,8 +1031,9 @@ async function autoBrowse() {
1006
1031
  }
1007
1032
 
1008
1033
  // `kaizen preview <url|image>` (cli/preview.ts) wrote what an agent changed: the Browser tab opens
1009
- // on it, inside the board. Never an outside window. The newest one per workspace opens once; one
1010
- // 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.
1011
1037
  const previewAt = new Map<string, number>();
1012
1038
  const fileUrl = (dir: string, image: string) => `${location.origin}/file?dir=${encodeURIComponent(dir)}&p=${encodeURIComponent(image)}`;
1013
1039
  // The latest preview written for this workspace, or null.
@@ -1016,17 +1042,17 @@ async function fetchPreview(dir: string, ws: string) {
1016
1042
  try {
1017
1043
  p = await (await fetch("/preview?dir=" + encodeURIComponent(dir))).json();
1018
1044
  } catch {}
1019
- const same = p.ws && (p.ws === ws || p.ws.startsWith(ws + "/") || ws.startsWith(p.ws + "/"));
1020
- 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;
1021
1046
  }
1022
1047
  async function pollPreview() {
1023
1048
  if (!ctx) return;
1024
1049
  const k = ctx.k, dir = ctx.dir;
1025
1050
  const p = await fetchPreview(dir, ctx.ws);
1026
- if (!p || ctx?.k !== k || (previewAt.get(k) ?? 0) >= p.at!) return;
1027
- const first = !previewAt.has(k);
1028
- previewAt.set(k, p.at!);
1029
- 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;
1030
1056
  if (p.image) {
1031
1057
  // A screenshot belongs in Preview; a live page in the Browser.
1032
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
 
@@ -1,50 +1,59 @@
1
- // Settings' sidebar, grouped as Orca's is. Only the page knows this: a setting's `group`
2
- // in cli/settings.ts still decides its scope and the TUI's headings.
1
+ // Settings' sidebar, grouped as macOS System Settings is: short groups of pages, each with
2
+ // its icon tile. Only the page knows this: a setting's `group` in cli/settings.ts still
3
+ // decides its scope and the TUI's headings.
3
4
  export type SettingsPage = { id: string; title: string; desc: string; ico: string };
4
5
  export const SETTINGS_NAV: [string, SettingsPage[]][] = [
5
- ["AI Capabilities", [
6
+ ["App", [
7
+ { id: "general", title: "General", desc: "About kaizen, storage, folders and how the app opens.", ico: "gear" },
8
+ { id: "appearance", title: "Appearance", desc: "Theme, color and motion in this browser.", ico: "sun" },
9
+ { id: "notifications", title: "Notifications", desc: "Notices and sounds in this browser.", ico: "inbox" },
10
+ { id: "keyboard", title: "Keyboard & Dictation", desc: "Shortcuts, and speech-to-text dictation run in the browser.", ico: "kbd" },
11
+ { id: "terminal", title: "Terminal", desc: "Board terminals and the terminal dashboard.", ico: "term" },
12
+ ]],
13
+ ["Agents", [
6
14
  { id: "agents", title: "Agents", desc: "Manage AI agents, set a default, and customize commands.", ico: "ai" },
7
- { id: "accounts", title: "AI Provider Accounts", desc: "Who is signed in to each AI tool kaizen runs. Add accounts only to switch between more than one.", ico: "link" },
8
- { id: "orchestration", title: "Orchestration", desc: "Split a run into workers, each in its own terminal. Off by default.", ico: "ai" },
15
+ { id: "models", title: "Models", desc: "The model each agent runs its stages and handoff sessions on.", ico: "mem" },
16
+ { id: "accounts", title: "AI Accounts", desc: "Who is signed in to each AI tool kaizen runs. Add accounts only to switch between more than one.", ico: "link" },
9
17
  { id: "skills", title: "Skills", desc: "What your agents can do. Changes apply to new sessions.", ico: "note" },
10
- { id: "voice", title: "Voice", desc: "Speech-to-text dictation, run in the browser.", ico: "mic" },
11
- ]],
12
- ["Set Up", [
13
- { id: "general", title: "General", desc: "Which settings you are editing, folders, and maintenance.", ico: "gear" },
14
- { id: "integrations", title: "Integrations", desc: "Request sources, your Google account, and web research.", ico: "link" },
15
- { id: "mobile", title: "Mobile", desc: "Open kaizen from your phone.", ico: "send" },
16
18
  ]],
17
- ["Workflows", [
19
+ ["Workflow", [
20
+ { id: "runs", title: "Runs", desc: "How a run is carried out: who builds, who reviews, and what it remembers.", ico: "play" },
18
21
  { id: "approvals", title: "Approvals", desc: "Where a run stops and waits for you.", ico: "check" },
19
22
  { id: "autofix", title: "Auto-fix", desc: "What happens to review findings.", ico: "bug" },
23
+ { id: "orchestration", title: "Orchestration", desc: "Split a run into workers, each in its own terminal. Off by default.", ico: "lgrid" },
20
24
  { id: "automations", title: "Automations", desc: "Schedules that start a run in this project.", ico: "clock" },
21
- { id: "git", title: "Git & Source Control", desc: "Branches and commits for each run.", ico: "pen" },
22
- { id: "terminal", title: "Terminal", desc: "The terminal dashboard.", ico: "term" },
25
+ { id: "git", title: "Git", desc: "Branches and commits for each run.", ico: "pen" },
23
26
  ]],
24
- ["Interface", [
25
- { id: "appearance", title: "Appearance", desc: "Theme, color and motion in this browser.", ico: "note" },
26
- { id: "notifications", title: "Notifications", desc: "Notices and sounds in this browser.", ico: "clock" },
27
- { id: "shortcuts", title: "Shortcuts", desc: "Keyboard shortcuts for common actions.", ico: "kbd" },
27
+ ["Connections", [
28
+ { id: "integrations", title: "Integrations", desc: "Request sources, your Google account, and web research.", ico: "ext" },
29
+ { id: "mobile", title: "Phone", desc: "Open kaizen from your phone, and send files to WhatsApp.", ico: "phone" },
28
30
  ]],
29
31
  ];
32
+ // Pages that were merged into another: an old `?page=` address still opens the right one.
33
+ const PAGE_ALIAS: Record<string, string> = { voice: "keyboard", shortcuts: "keyboard" };
34
+ export const pageId = (id: string) => PAGE_ALIAS[id] ?? id;
35
+ // Subsections that should come first on their page, whatever order their rows arrive in.
36
+ export const SUB_ORDER: Record<string, string[]> = { general: ["Storage", "Folders", "App"], keyboard: ["Shortcuts", "Dictation"] };
30
37
  // First match wins: [key pattern, page, subsection].
31
38
  const PLACES: [RegExp, string, string][] = [
32
- [/^(preset|runner|explore\.|build\.|review\.executor)/, "agents", "Workflow"],
33
- [/^(subagents\.|agent\.model\.)/, "agents", "Models"],
34
- [/^agent\.handoff_model\./, "agents", "Handoff session"],
39
+ [/^(preset|runner|explore\.|build\.|review\.executor)/, "runs", "Workflow"],
40
+ [/^review\.(write_memory|memory_max_lines)$/, "runs", "Memory"],
41
+ [/^(subagents\.|agent\.model\.)/, "models", "Models"],
42
+ [/^agent\.handoff_model\./, "models", "Handoff session"],
35
43
  [/^agent\.default$/, "agents", "Default agent"],
36
44
  [/^agent\./, "agents", "Running agents"],
37
45
  [/^orchestration\./, "orchestration", "Workers"],
38
- [/^dictation\./, "voice", "Dictation"],
46
+ [/^dictation\./, "keyboard", "Dictation"],
39
47
  [/^sources\./, "integrations", "Request sources"],
40
48
  [/^(mode|approvals\.|auto_accept)/, "approvals", "Approvals"],
41
49
  [/^auto_fix\./, "autofix", "Auto-fix"],
42
50
  [/^auto_guard\./, "autofix", "Auto mode guard"],
43
51
  [/^git\./, "git", "Git"],
44
52
  [/^ui\./, "terminal", "Terminal"],
45
- [/^board\.chat_hotkey$/, "shortcuts", "Shortcuts"],
53
+ [/^board\.chat_hotkey$/, "keyboard", "Shortcuts"],
54
+ [/^board\.(projects_dir|video_dir)$/, "general", "Folders"],
46
55
  [/^board\./, "general", "App"],
47
- [/^(review\.|state\.)/, "general", "Project"],
56
+ [/^state\./, "general", "Storage"],
48
57
  ];
49
58
  // A setting nobody has placed yet still shows, on General.
50
59
  export const placeOf = (key: string): [string, string] => {