kaizen-agent 1.59.1 → 1.60.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/cli/add-project.test.ts +169 -0
  2. package/cli/add-project.ts +132 -0
  3. package/cli/board.test.ts +15 -0
  4. package/cli/chat.ts +1 -1
  5. package/cli/dashboard.ts +6 -2
  6. package/cli/install.test.ts +1 -1
  7. package/cli/install.ts +18 -9
  8. package/cli/pty.test.ts +82 -3
  9. package/cli/pty.ts +122 -6
  10. package/cli/restart.test.ts +169 -0
  11. package/cli/settings.test.ts +35 -0
  12. package/cli/settings.ts +69 -18
  13. package/cli/state.test.ts +119 -3
  14. package/cli/state.ts +171 -13
  15. package/cli/usage.test.ts +130 -1
  16. package/cli/web-accept.test.ts +54 -0
  17. package/cli/web-symlink.test.ts +28 -0
  18. package/cli/web.ts +320 -100
  19. package/cli/worktree.test.ts +43 -1
  20. package/cli/worktree.ts +97 -2
  21. package/cli/writeback.ts +1 -1
  22. package/package.json +1 -1
  23. package/skills/kaizen/SKILL.md +5 -1
  24. package/skills/kaizen/config.default.yml +15 -2
  25. package/skills/kaizen/settings.md +1 -0
  26. package/skills/kaizen/spec-main.md +28 -2
  27. package/skills/kaizen-help/SKILL.md +1 -0
  28. package/web/board/add-project.ts +136 -0
  29. package/web/board/api.ts +1 -1
  30. package/web/board/badge.ts +5 -5
  31. package/web/board/cards.ts +11 -3
  32. package/web/board/context.ts +1 -0
  33. package/web/board/fixes.ts +3 -2
  34. package/web/board/git.ts +2 -0
  35. package/web/board/home.ts +7 -1
  36. package/web/board/ideas.ts +20 -3
  37. package/web/board/live.ts +1 -1
  38. package/web/board/main.ts +26 -9
  39. package/web/board/panel.ts +18 -3
  40. package/web/board/phone.ts +26 -3
  41. package/web/board/projects.ts +6 -85
  42. package/web/board/run-pick.ts +41 -0
  43. package/web/board/run-view.ts +261 -104
  44. package/web/board/settings.ts +42 -5
  45. package/web/board/store.ts +3 -1
  46. package/web/board/toast.ts +4 -1
  47. package/web/board/views.ts +6 -2
  48. package/web/board/workspace.ts +125 -38
  49. package/web/board/ws-board-ui.ts +84 -0
  50. package/web/board/ws-board.test.ts +71 -0
  51. package/web/board/ws-board.ts +45 -0
  52. package/web/board/ws-tabs.test.ts +171 -0
  53. package/web/board/ws-tabs.ts +170 -0
  54. package/web/board.html +92 -43
  55. package/web/board.js +44 -43
  56. package/web/notebook.js +24 -25
  57. package/web/notes.html +26 -21
  58. package/web/term.js +1 -1
  59. package/web/video.html +26 -21
  60. package/web/video.js +56 -57
@@ -1,9 +1,14 @@
1
- // The run workspace (?view=run&dir=&id=, or &idea=<text> for an idea): the card's panel
2
- // docked at the right as an icon strip (panel.ts draws it; open() fills it), and a tabbed
3
- // centre: the run's agent, shells started with POST /shell, the project's localhost, the
4
- // run's Preview and project notes. Terminal tabs are kzTerm mounts on /pty that live as
5
- // long as their tab, so a tab switch or a /state tick never reconnects them. Split right
6
- // or down shows a second tab beside the first, sized with the Terminal page's handles.
1
+ // The workspace centre (?view=ws&dir=&ws=; a run's or idea's old address resolves to its
2
+ // workspace and picks that run in the panel): a tab bar over one folder holding terminals and the
3
+ // Browser, never runs. Agent terminals are tabs, named by stage for a run's ("Build · Claude"),
4
+ // beside shells started with POST /shell {ws}, the project's localhost, the Preview, project
5
+ // notes and History (finished runs, read-only in the panel). The run panel (#panel, drawn by
6
+ // panel.ts) docks on the right and shows one run, chosen in its picker (run-pick.ts); the centre
7
+ // never follows it. A workspace with no tab opens a shell in its folder. Terminal tabs are
8
+ // kzTerm mounts on /pty that live as long as their tab, so a tab switch or a /state tick never
9
+ // reconnects them. Split right or down shows a second tab beside the first, sized with the
10
+ // Terminal page's handles.
11
+ import { pick } from "./projects.ts";
7
12
  import { store } from "./store.ts";
8
13
  import { toast } from "./toast.ts";
9
14
  import { $, html, ico, raw } from "./dom.ts";
@@ -13,34 +18,25 @@ import { termLoad } from "./agent-term.ts";
13
18
  import { load, post } from "./api.ts";
14
19
  import { attach, md, preview } from "./markdown.ts";
15
20
  import { layout } from "./terms.ts";
16
- import { cardHref, markCurrent, railData } from "./workspace.ts";
21
+ import { cardHref, markCurrent, railData, titleOf, wsHref, wsOfCard } from "./workspace.ts";
22
+ import { type Node, awaiting, chosen, finished, historyOf, leaves, liveIn, loopbackUrl, migrate, pickable, prune, reviewing, stageTabs, toOpen, wsKey } from "./ws-tabs.ts";
23
+ import { drawPick, hidePick, initPick, setOpen } from "./run-pick.ts";
24
+ import { age } from "./labels.ts";
17
25
  import { go } from "./views.ts";
26
+ import { isPhone } from "./phone.ts";
18
27
 
19
- type Tab = { id: string; kind: "agent" | "shell" | "local" | "preview" | "note" | "wait"; title: string; key?: string; note?: string; agent?: string };
20
- // Per run: the extra items opened (localhost, preview, notes), agent items closed, and the
21
- // screens. A screen is one tab of the bar: one or more items side by side or stacked.
22
- // A screen's layout is a tmux-style tree: a leaf is an item id; a split holds two or more
23
- // children side by side ("cols") or stacked ("rows"), with their relative sizes.
24
- type Node = string | { dir: "cols" | "rows"; kids: Node[]; sizes: number[] };
28
+ type Tab = { id: string; kind: "agent" | "shell" | "local" | "preview" | "note" | "wait" | "history"; title: string; key?: string; note?: string; agent?: string };
29
+ // Per workspace: the extra items opened (localhost, preview, notes, History),
30
+ // tabs closed, and the screens. A screen is one tab of the bar: one or more items side by
31
+ // side or stacked.
25
32
  type Screen = { id: string; tree: Node; focus: string };
26
- const leaves = (n: Node): string[] => (typeof n === "string" ? [n] : n.kids.flatMap(leaves));
27
- // Drops ids no longer open; a split left with one child becomes that child.
28
- function prune(n: Node, keep: (id: string) => boolean): Node | null {
29
- if (typeof n === "string") return keep(n) ? n : null;
30
- const kids: Node[] = [],
31
- sizes: number[] = [];
32
- n.kids.forEach((k, i) => {
33
- const p = prune(k, keep);
34
- if (p) (kids.push(p), sizes.push(n.sizes[i] ?? 1));
35
- });
36
- return !kids.length ? null : kids.length === 1 ? kids[0] : { dir: n.dir, kids, sizes };
37
- }
38
33
  // tmux: the focused pane splits in two, the new item right of or under it.
39
34
  function splitAt(n: Node, at: string, add: string, dir: "cols" | "rows", before = false): Node {
40
35
  if (typeof n === "string") return n === at ? { dir, kids: before ? [add, n] : [n, add], sizes: [1, 1] } : n;
41
36
  return { ...n, kids: n.kids.map((k) => splitAt(k, at, add, dir, before)) };
42
37
  }
43
- type Saved = { tabs: Tab[]; hidden: string[]; screens: Screen[]; on: string | null };
38
+ // seen: the runs that already opened the Browser on their Preview, so a run does it once.
39
+ type Saved = { tabs: Tab[]; hidden: string[]; screens: Screen[]; on: string | null; seen?: string[] };
44
40
  const ALL: Record<string, Saved> = (() => {
45
41
  try {
46
42
  return JSON.parse(localStorage.getItem("kz-runtabs") || "{}");
@@ -53,18 +49,24 @@ const save = () => {
53
49
  localStorage.setItem("kz-runtabs", JSON.stringify(ALL));
54
50
  } catch {}
55
51
  };
52
+ // The workspace shown, and the card whose panel is up (the picker's).
53
+ let ctx: { dir: string; ws: string; k: string } | null = null;
56
54
  let card: any = null;
57
55
  let shells: any[] = [];
58
56
  let noPty = false;
59
57
  // Every agent installed for this project (from /agents), each offered as a bare session.
60
58
  let agents: { name: string; cmd: string }[] = [];
59
+ let defAgent = "";
61
60
  // The agents with their own mark in the sprite; the rest show the generic one.
62
61
  const MARKS = ["claude", "codex", "gemini"];
63
62
  // Tab id -> its pane, and for a terminal the function that unmounts it.
64
63
  const panes = new Map<string, { el: HTMLElement; off: (() => void) | null }>();
65
- const runKey = (c) => key(c);
64
+ const byKey = (k: string) => store.S.cards.find((x) => key(x) === k);
66
65
  const saved = (): Saved => {
67
- const s = (ALL[runKey(card)] ||= { tabs: [], hidden: [], screens: [], on: null });
66
+ const s = (ALL[ctx!.k] ||= { tabs: [], hidden: [], screens: [], on: null });
67
+ // Layouts saved while runs were tabs: those tabs are gone, the panel picks runs now.
68
+ s.tabs = s.tabs.filter((t: any) => t.kind !== "run");
69
+ s.hidden = s.hidden.filter((h) => !h.startsWith("rn:"));
68
70
  if (!Array.isArray(s.screens) || s.screens.some((sc: any) => !sc.tree)) (s.screens = []), delete (s as any).split; // older saves
69
71
  return s;
70
72
  };
@@ -90,68 +92,121 @@ function screens(): Screen[] {
90
92
  }
91
93
  const loopback = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);
92
94
 
95
+ const AGENTS = ["claude", "codex", "gemini", "agy", "opencode", "cursor"];
96
+ const wsCards = () => (ctx ? liveIn(store.S.cards, ctx.dir, ctx.ws, wsOfCard) : []);
97
+
93
98
  function tabs(): Tab[] {
94
99
  const s = saved(),
95
100
  out: Tab[] = [];
96
- // Every agent session the run has on this board, each its own tab.
97
- const keys: string[] = card.pty ? card.pty.all ?? [card.pty.key] : [];
98
- const runAgent = ["claude", "codex", "gemini", "agy", "opencode", "cursor"].find((a) => card.tags?.includes(a)) ?? undefined;
99
101
  const named = (a?: string) => agents.find((x) => x.cmd === a)?.name ?? "Agent";
100
- keys.forEach((k, i) => out.push({ id: "agent:" + k, kind: "agent", agent: runAgent, title: named(runAgent) + (keys.length > 1 ? " " + (i + 1) : ""), key: k }));
101
- for (const sh of shells.filter((x) => x.run === runKey(card))) out.push({ id: "sh:" + sh.key, kind: sh.agent ? "agent" : "shell", agent: sh.agent || undefined, title: sh.title, key: sh.key });
102
- // The run's own session is running in another terminal: a tab that says so.
103
- if (elsewhere.has(runKey(card))) out.push({ id: "wait", kind: "wait", agent: "claude", title: named("claude") });
104
- return [...out.filter((t) => !s.hidden.includes(t.id)), ...s.tabs];
102
+ const live = wsCards(),
103
+ liveKeys = new Set(live.map(key));
104
+ // Each live run's terminals: its stage terminals ("Build · Claude"), other sessions, shells, the waiting note.
105
+ for (const c of live) {
106
+ const k = key(c),
107
+ runAgent = AGENTS.find((a) => c.tags?.includes(a)) ?? undefined;
108
+ for (const t of stageTabs(c, named(runAgent))) out.push({ id: "agent:" + t.key, kind: "agent", agent: runAgent, title: t.title, key: t.key });
109
+ for (const sh of shells.filter((x) => x.run === k)) out.push({ id: "sh:" + sh.key, kind: sh.agent ? "agent" : "shell", agent: sh.agent || undefined, title: sh.title, key: sh.key });
110
+ // The run's own session is running in another terminal: a tab that says so.
111
+ if (elsewhere.has(k)) out.push({ id: "wait:" + k, kind: "wait", agent: "claude", title: named("claude") });
112
+ }
113
+ // The workspace's own shells and agents, and those of its finished runs.
114
+ const owned = new Set(store.S.cards.filter((c) => c.state === ctx!.dir && wsOfCard(c) === ctx!.ws).map(key));
115
+ for (const sh of shells.filter((x) => x.run === ctx!.k || (owned.has(x.run) && !liveKeys.has(x.run))))
116
+ out.push({ id: "sh:" + sh.key, kind: sh.agent ? "agent" : "shell", agent: sh.agent || undefined, title: sh.title, key: sh.key });
117
+ // Opened by hand: History, localhost, Preview, notes.
118
+ const mine = s.tabs.map((t) => (t.kind === "local" ? { ...t, title: "Browser" } : t)); // "local" was saved before the rename
119
+ const all = [...out.filter((t) => !s.hidden.includes(t.id)), ...mine];
120
+ return all.filter((t, i) => all.findIndex((x) => x.id === t.id) === i);
105
121
  }
106
122
  // An agent's tab shows the agent's own mark when the sprite has one.
107
- const icon = (t: Tab) => (t.agent && MARKS.includes(t.agent) ? raw(`<svg><use href="#i-${t.agent}"/></svg>`) : ico({ agent: "ai", shell: "term", local: "link", preview: "eye", note: "note", wait: "ai" }[t.kind]));
123
+ const icon = (t: Tab) =>
124
+ t.agent && MARKS.includes(t.agent) ? raw(`<svg><use href="#i-${t.agent}"/></svg>`) : ico({ agent: "ai", shell: "term", local: "link", preview: "eye", note: "note", wait: "ai", history: "note" }[t.kind]);
108
125
  const elsewhere = new Set<string>();
109
126
 
127
+ let switched: string | null = null; // the project a deep link last switched the board to
128
+ const none = (t: string) => void ($("rtabs").innerHTML = String(html`<span class="rnone">${t}</span>`));
110
129
  // Called by go("run") and on every /state: draws the tab strip and keeps the panes.
111
- export async function showRunView() {
130
+ export async function showRunView(nav = false) {
112
131
  const p = new URLSearchParams(location.search),
113
132
  dir = p.get("dir"),
114
133
  id = p.get("id"),
115
134
  idea = p.get("idea");
116
- const find = (cs) => cs.find((x) => x.state === dir && (id ? x.kind === "run" && x.id === id : x.kind === "idea" && x.text === idea));
117
- const c = find(store.S.cards);
118
- // A launched idea becomes a run: its agent session moves to the run's card, and the view follows.
119
- const pk = idea && (c ?? card)?.kind === "idea" && (c ?? card)?.pty?.key;
120
- const run = pk && store.S.cards.find((x) => x.kind === "run" && x.state === dir && (x.pty?.key === pk || x.pty?.all?.includes(pk)));
121
- if (run) {
122
- history.replaceState(null, "", cardHref(run));
123
- markCurrent();
124
- return showRunView();
125
- }
126
- if (!c) {
127
- // A project this board is not showing: the all-projects board has it.
128
- if (!store.all && find(railData().cards)) location.href = "/?all=1&" + p.toString();
129
- else $("rtabs").innerHTML = String(html`<span class="rnone">That ${id ? "run" : "idea"} is not on this board.</span>`);
130
- return;
135
+ let ws = p.get("ws"),
136
+ want: any = null; // the card the address names, whose tab is selected
137
+ // A project this board is not showing: a deep link names its project, switched to once, as a rail click does.
138
+ const away = async () => {
139
+ if (store.all || !dir || dir === store.dir || dir === switched) return false;
140
+ switched = dir;
141
+ await pick(dir).catch(() => {});
142
+ return true;
143
+ };
144
+ if (p.get("view") === "ws" && ws) {
145
+ if (await away()) return showRunView(nav);
146
+ } else {
147
+ const find = (cs) => cs.find((x) => x.state === dir && (id ? x.kind === "run" && x.id === id : x.kind === "idea" && x.text === idea));
148
+ const c = find(store.S.cards);
149
+ // A launched idea becomes a run: its agent session moves to the run's card, and the view follows.
150
+ const pk = idea && (c ?? card)?.kind === "idea" && (c ?? card)?.pty?.key;
151
+ const run = pk && store.S.cards.find((x) => x.kind === "run" && x.state === dir && (x.pty?.key === pk || x.pty?.all?.includes(pk)));
152
+ if (run) {
153
+ history.replaceState(null, "", cardHref(run));
154
+ markCurrent();
155
+ return showRunView(nav);
156
+ }
157
+ if (!c) {
158
+ if (await away()) return showRunView(nav);
159
+ if (!store.all && find(railData().cards)) location.href = "/?all=1&" + p.toString();
160
+ else (stopPanes(), (ctx = card = null), none(`That ${id ? "run" : "idea"} is not on this board.`));
161
+ return;
162
+ }
163
+ want = c;
164
+ ws = wsOfCard(c);
131
165
  }
132
- const fresh = !card || runKey(card) !== runKey(c);
133
- // Each run has its own centre: switching runs unmounts this one's panes (its shells keep running on the server).
134
- if (fresh) stopPanes();
135
- card = c;
136
- if (fresh || store.openKey !== key(c)) open(c);
166
+ if (!dir || !ws) return void (stopPanes(), (ctx = card = null), none("That workspace is not on this board."));
167
+ const k = wsKey(dir, ws);
168
+ const fresh = ctx?.k !== k;
169
+ // Each workspace has its own centre: switching unmounts this one's panes (its shells keep running on the server).
170
+ if (fresh) (stopPanes(), (card = null), (ctx = { dir, ws, k }));
171
+ 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
172
+ // The header titles a phone's workspace: the run, else the branch.
173
+ const w = railData().projects?.find((x) => x.dir === dir)?.workspaces?.find((x) => x.path === ws);
174
+ document.querySelector(".hdr h1")!.textContent = want ? titleOf(want) : w?.branch || ws.split(/[\\/]/).pop() || "Workspace";
175
+ // Layouts saved per run before workspaces move to their workspace; keys no card owns stay.
176
+ if (migrate(ALL, store.S.cards, key, wsOfCard)) save();
137
177
  try {
138
- const r = await fetch("/shells?dir=" + encodeURIComponent(c.state));
178
+ const r = await fetch("/shells?dir=" + encodeURIComponent(dir));
139
179
  shells = r.ok ? await r.json() : [];
140
180
  } catch {}
141
181
  if (fresh) {
142
182
  try {
143
- agents = (await (await fetch("/agents?dir=" + encodeURIComponent(c.state))).json()).agents ?? [];
183
+ const d = await (await fetch("/agents?dir=" + encodeURIComponent(dir))).json();
184
+ agents = d.agents ?? [];
185
+ defAgent = d.default ?? "";
144
186
  } catch {}
145
187
  }
146
- if (card !== c) return;
147
- // Nothing to show (no board-launched agent, no shell, no tab saved): the run's own Claude
148
- // session resumed here, else a shell in the project, once per run per visit, so the centre
149
- // is never blank. Only the run's recorded session is ever resumed; nothing new is started.
150
- if (!tabs().length && !noPty && !autoShell.has(runKey(c))) {
151
- autoShell.add(runKey(c));
152
- return void (c.kind === "run" ? openAgent() : newPty());
188
+ if (ctx?.k !== k) return;
189
+ // Every navigation (a notification, a Board card, a link) picks the card's run in the panel, even for an address already open: a finished run opens read-only.
190
+ // A fresh visit forgets the old pick (waiting first again); one made during the visit stays.
191
+ if (fresh) picked.delete(k);
192
+ if (want?.kind === "run" && (nav || fresh)) picked.set(k, key(want));
193
+ // A workspace with nothing open starts a shell in its folder (no agent, no run). A live run whose own Claude
194
+ // session is not open anywhere on the board is resumed here, once per visit.
195
+ if (!noPty) {
196
+ if (!tabs().length && !autoShell.has(k)) return void (autoShell.add(k), newPty());
197
+ if (want && want.kind === "run" && !finished(want) && !want.pty && !shells.some((x) => x.run === key(want)) && !autoShell.has(key(want))) {
198
+ autoShell.add(key(want));
199
+ void openAgent(want, false, false);
200
+ }
153
201
  }
154
- draw();
202
+ if (!showTerm()) draw();
203
+ }
204
+ // The terminal the sidebar asked for, selected once the workspace's tabs are known.
205
+ let wantTerm: string | null = null;
206
+ function showTerm() {
207
+ const t = wantTerm && tabs().find((x) => x.key === wantTerm);
208
+ wantTerm = null;
209
+ return !!t && (show(t.id), true);
155
210
  }
156
211
  const autoShell = new Set<string>();
157
212
 
@@ -162,15 +217,18 @@ function draw() {
162
217
  cur = scs.find((sc) => sc.id === s.on);
163
218
  const item = (id: string) => ts.find((t) => t.id === id)!;
164
219
  const PTY = !noPty;
165
- const menu = html`<div class="menu-pop">${PTY ? html`<button data-n="shell">${ico("term")}<span>Shell<small>a terminal in the project folder</small></span></button>` : ""}<button data-n="local">${ico("link")}<span>Localhost<small>the project's dev server</small></span></button><button data-n="preview">${ico("eye")}<span>Preview<small>the run's Preview</small></span></button>${PTY ? agents.map((a) => html`<button data-n="agent:${a.cmd}">${MARKS.includes(a.cmd) ? raw(`<svg><use href="#i-${a.cmd}"/></svg>`) : ico("ai")}<span>${a.name} session<small>the agent alone, no run</small></span></button>`) : ""}</div>`;
220
+ const mark = (a) => (MARKS.includes(a.cmd) ? raw(`<svg><use href="#i-${a.cmd}"/></svg>`) : ico("ai"));
221
+ const dflt = agents.find((a) => a.cmd === defAgent);
222
+ const menu = html`<div class="menu-pop">${PTY && dflt ? html`<button data-n="agent:${dflt.cmd}">${mark(dflt)}<span>New agent here<small>${dflt.name} in this folder</small></span></button>` : ""}${PTY ? html`<button data-n="shell">${ico("term")}<span>Shell<small>a terminal in this folder</small></span></button>` : ""}<button data-n="local">${ico("link")}<span>Browser<small>localhost pages, e.g. the dev server</small></span></button><button data-n="preview">${ico("eye")}<span>Preview<small>the run's Preview</small></span></button><button data-n="history">${ico("note")}<span>History<small>finished runs in this workspace</small></span></button>${PTY ? agents.filter((a) => a !== dflt).map((a) => html`<button data-n="agent:${a.cmd}">${mark(a)}<span>${a.name} session<small>the agent alone, no run</small></span></button>`) : ""}</div>`;
166
223
  $("rtabs").innerHTML = String(
167
224
  html`${scs.map((sc) => {
168
225
  const ids = leaves(sc.tree),
169
226
  first = item(ids[0]),
170
227
  title = ids.map((id) => item(id).title).join(" + ");
171
- return html`<button class="rtab${sc.id === s.on ? " on" : ""}" data-t="${sc.id}" title="${title}">${icon(first)}<span>${title}</span><i data-xs="${sc.id}" role="button" aria-label="Close ${title}" title="Close tab">×</i></button>`;
172
- })}<details class="radd" data-mode="tab"><summary class="rbtn" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><span class="sp"></span>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="rbtn" 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="rbtn" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}<button class="rbtn" id="rside" title="Show or hide the run panel" aria-label="Show or hide the run panel" aria-pressed="${String(document.body.classList.contains("rflip"))}">${ico("open")}</button>`,
228
+ 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>`;
229
+ })}<details class="radd" data-mode="tab"><summary class="rbtn" title="New tab" aria-label="New tab">${ico("plus")}</summary>${menu}</details><span class="sp"></span>${cur ? html`<details class="radd rsplit" data-mode="cols"><summary class="rbtn" 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="rbtn" title="Split down: add to this tab" aria-label="Split down">${ico("lrows")}</summary>${menu}</details>` : ""}`,
173
230
  );
231
+ $("rside").setAttribute("aria-pressed", String(document.body.classList.contains("rflip")));
174
232
  $("rtabs").querySelector(".rtab.on")?.scrollIntoView({ block: "nearest", inline: "nearest" });
175
233
  // Panes: made once per item, kept (hidden) while it is open, so terminals never reconnect.
176
234
  const box = $("rpanes");
@@ -187,6 +245,7 @@ function draw() {
187
245
  p.el.classList.toggle("split", shown.length > 1);
188
246
  p.el.classList.toggle("focus", shown.length > 1 && id === cur?.focus);
189
247
  p.el.querySelector(".ph span")!.textContent = item(id)?.title ?? "";
248
+ if (item(id)?.kind === "history") fillHistory(p.el);
190
249
  }
191
250
  // The tree is rebuilt only when it changes: moving a pane in the DOM reloads its frame.
192
251
  const sig = cur ? cur.id + JSON.stringify(cur.tree) : "";
@@ -198,10 +257,47 @@ function draw() {
198
257
  }
199
258
  // One empty note at most: every draw used to append another.
200
259
  box.querySelector(".rempty")?.remove();
201
- if (!scs.length) box.insertAdjacentHTML("beforeend", String(html`<div class="empty rempty"><b>No tabs open</b><p>Open a shell, the project's localhost or the Preview with +.</p></div>`));
260
+ if (!scs.length) box.insertAdjacentHTML("beforeend", String(html`<div class="empty rempty"><b>No tabs open</b><p>Open an agent, a shell, the project's localhost or the Preview with +.</p></div>`));
261
+ mountPanel();
202
262
  wire();
203
263
  }
204
264
 
265
+ // The run panel (#panel) stays docked on the right of the centre and shows one run: the one picked
266
+ // in its header (run-pick.ts), first the run waiting on you, else the newest. A pick is sticky; a
267
+ // run that starts waiting later does not replace it: the picker's trigger and, with the panel
268
+ // collapsed, the panel button show a dot. With no run the panel is parked.
269
+ const picked = new Map<string, string>();
270
+ let pickOpen = false;
271
+ // Shows a run in the panel (a picker row, a History row); the centre stays as it is.
272
+ const pickRun = (k: string) => (picked.set(ctx!.k, k), draw()); // the sidebar count asked for the picker dropped down
273
+ function mountPanel() {
274
+ const live = pickable(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
275
+ hist = historyOf(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
276
+ c = chosen(live, hist, picked.get(ctx!.k), key);
277
+ $("panel").classList.toggle("parked", !c);
278
+ $("rside").hidden = !c;
279
+ // Collapsed (a phone: sheet down) and a run waits: a dot on the panel button, no pop-open.
280
+ $("rside").toggleAttribute("data-dot", document.body.classList.contains("rflip") !== isPhone() && live.some(awaiting));
281
+ if (!c) return void ((card = null), (pickOpen = false), hidePick());
282
+ picked.set(ctx!.k, key(c));
283
+ $("panel").classList.toggle("ro", hist.includes(c)); // a run from History: no edit buttons (the commit and push ones stay)
284
+ card = c;
285
+ drawPick(live, hist, c);
286
+ if (store.openKey !== key(c)) void open(c, false);
287
+ if (pickOpen) (setOpen(true), (pickOpen = false));
288
+ }
289
+ // History: the workspace's finished runs, newest first; one opens read-only.
290
+ function fillHistory(el: HTMLElement) {
291
+ const list = historyOf(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
292
+ now = Date.now();
293
+ const box = el.querySelector(".rhist")!;
294
+ box.innerHTML = String(
295
+ list.length
296
+ ? html`${list.map((c) => html`<button class="rrow" data-hist="${key(c)}"><span class="si ${stateOf(c)}"></span><b>${titleOf(c)}</b><small>${c.status} · ${age(c.moved ?? now, now)} ago</small></button>`)}`
297
+ : html`<p class="rnone">No finished runs in this workspace yet.</p>`,
298
+ );
299
+ }
300
+
205
301
  let shownSig = "";
206
302
  // Moves an item out of its tab into another one (split beside a pane there, or next to its
207
303
  // focused pane), or into a tab of its own (to = null). Terminals keep running; frames reload.
@@ -282,7 +378,10 @@ function makePane(t: Tab) {
282
378
  const p = { el, off: null as null | (() => void) };
283
379
  panes.set(t.id, p);
284
380
  $("rpanes").append(el);
285
- if (t.kind === "agent" || t.kind === "shell") {
381
+ if (t.kind === "history") {
382
+ el.insertAdjacentHTML("beforeend", String(html`<div class="rhist md"></div>`));
383
+ fillHistory(el);
384
+ } else if (t.kind === "agent" || t.kind === "shell") {
286
385
  const term = document.createElement("div");
287
386
  term.className = "term";
288
387
  el.append(term);
@@ -294,16 +393,17 @@ function makePane(t: Tab) {
294
393
  } else if (t.kind === "wait")
295
394
  el.insertAdjacentHTML(
296
395
  "beforeend",
297
- String(html`<div class="empty rwait"><b>This run's agent is running in another terminal</b><p>One conversation cannot run in two places. Close it there, then open it here.</p><button type="button" class="rwin" data-b="recheck">${ico("refresh")}<span>Open here</span></button></div>`),
396
+ String(html`<div class="empty rwait"><b>This run's agent is running in another terminal</b><p>One conversation cannot run in two places. Close it there, then open it here.</p><button type="button" class="rwin" data-b="recheck" data-k="${t.id.slice(5)}">${ico("refresh")}<span>Open here</span></button></div>`),
298
397
  );
299
398
  else if (t.kind === "local") browser(el);
300
- else if (t.kind === "note") el.insertAdjacentHTML("beforeend", String(html`<iframe class="rframe" title="${t.title}" src="/notebook?dir=${encodeURIComponent(card.state)}&note=${encodeURIComponent(t.note!)}&embed=1"></iframe>`));
399
+ else if (t.kind === "note") el.insertAdjacentHTML("beforeend", String(html`<iframe class="rframe" title="${t.title}" src="/notebook?dir=${encodeURIComponent(ctx!.dir)}&note=${encodeURIComponent(t.note!)}&embed=1"></iframe>`));
301
400
  else void previewPane(el);
302
401
  }
303
402
 
304
- // The localhost tab: a URL bar over an iframe. The URL is kept per project.
403
+ // The Browser tab: a URL bar over an iframe. The address is kept per workspace; a run's
404
+ // Preview sets it when the run reaches review (autoBrowse).
305
405
  function browser(el: HTMLElement) {
306
- const k = "kz-browse:" + card.state;
406
+ const k = "kz-browse:" + ctx!.k;
307
407
  let url = "http://localhost:3000";
308
408
  try {
309
409
  url = localStorage.getItem(k) || url;
@@ -312,16 +412,19 @@ function browser(el: HTMLElement) {
312
412
  fwd: string[] = [];
313
413
  el.insertAdjacentHTML(
314
414
  "beforeend",
315
- String(html`<form class="urlbar"><button type="button" data-b="back" title="Back" aria-label="Back">‹</button><button type="button" data-b="fwd" title="Forward" aria-label="Forward">›</button><button type="button" data-b="reload" title="Reload" aria-label="Reload">${ico("refresh")}</button><input class="sel" aria-label="Address" spellcheck="false" value="${url}">${winBtn(url)}</form>`),
415
+ String(html`<form class="urlbar"><button type="button" data-b="back" title="Back" aria-label="Back">‹</button><button type="button" data-b="fwd" title="Forward" aria-label="Forward">›</button><button type="button" data-b="reload" title="Reload" aria-label="Reload">${ico("refresh")}</button><input class="sel" aria-label="Address" spellcheck="false" value="${url}"><a class="rwin" data-b="tab" target="_blank" rel="noopener" href="${url}" title="Open in a new browser tab">${ico("popout")}<span>New tab</span></a></form>`),
316
416
  );
317
417
  const f = el.querySelector("form")!,
318
418
  inp = f.querySelector("input")!,
319
419
  ext = f.querySelector<HTMLAnchorElement>("a.rwin");
420
+ (el as any).browseTo = (u: string) => go(u);
320
421
  // On a phone over the tailnet, localhost is the phone itself: framing it shows nothing useful.
321
422
  const local = (u) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(u);
322
423
  const frame = document.createElement("iframe");
323
424
  frame.className = "rframe";
324
- frame.title = "localhost";
425
+ frame.title = "Browser";
426
+ // Dev apps run; a framed page cannot navigate the board itself (no allow-top-navigation).
427
+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads");
325
428
  const note = document.createElement("p");
326
429
  note.className = "rnote";
327
430
  const far = "This page is on the computer running the board; from this device localhost is the device itself. Use Open in browser on that computer.";
@@ -349,8 +452,9 @@ function browser(el: HTMLElement) {
349
452
  frame.hidden = true;
350
453
  frame.removeAttribute("src");
351
454
  note.hidden = false;
352
- note.textContent = `${new URL(u).host} does not allow being shown inside another page. `;
353
- note.insertAdjacentHTML("beforeend", String(winBtn(u)));
455
+ // The fallback card: the page refuses to be framed, so offer it outside the board.
456
+ note.textContent = "";
457
+ note.insertAdjacentHTML("beforeend", String(html`<b>This page refuses to be shown inside the board</b>${new URL(u).host} sends a header that forbids framing. <a class="rwin" target="_blank" rel="noopener" href="${u}">${ico("popout")}<span>Open in new tab</span></a>${winBtn(u)}`));
354
458
  })
355
459
  .catch(() => {});
356
460
  };
@@ -372,11 +476,11 @@ function browser(el: HTMLElement) {
372
476
 
373
477
  // A Chromium app window on the board's computer (POST /open-url): for dev servers that
374
478
  // refuse to be framed. Only offered when the page itself is on that computer.
375
- // One labelled button: on the board's computer a Chromium app window, elsewhere a new tab.
479
+ // One labelled button: a Chromium app window on the board's computer, for loopback pages only.
376
480
  const winBtn = (u: string) =>
377
- loopback
378
- ? html`<button type="button" class="rwin" data-b="win" title="Open in a browser window">${ico("popout")}<span>Open in browser</span></button>`
379
- : html`<a class="rwin" target="_blank" rel="noopener" href="${u}">${ico("popout")}<span>Open in browser</span></a>`;
481
+ loopback && loopbackUrl(u)
482
+ ? html`<button type="button" class="rwin" data-b="win" title="Open in an app window">${ico("popout")}<span>Open in app window</span></button>`
483
+ : "";
380
484
  async function openWindow(u: string) {
381
485
  const r = await fetch("/open-url", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url: u }) }).catch(() => null);
382
486
  if (!r?.ok) toast("Could not open a browser window" + (r ? ": " + ((await r.json().catch(() => ({}))) as any).error : ""));
@@ -386,13 +490,13 @@ async function openWindow(u: string) {
386
490
  // app link when it names a localhost address. The address is framed only when the Preview
387
491
  // has no images: the dev server a run used is often gone, and a dead frame hides the proof.
388
492
  async function previewPane(el: HTMLElement) {
389
- let doc = store.runDoc && store.runDoc.id === card.id ? store.runDoc : null;
390
- if (!doc && card.kind === "run")
493
+ let doc = store.runDoc && store.runDoc.id === card?.id ? store.runDoc : null;
494
+ if (!doc && card?.kind === "run")
391
495
  try {
392
496
  doc = await (await fetch(`/run/${encodeURIComponent(card.id)}?dir=${encodeURIComponent(card.state)}`)).json();
393
497
  } catch {}
394
498
  const pv = doc && preview(doc.impl);
395
- const url = pv && /https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?[^\s)`'"<>]*/.exec(pv)?.[0];
499
+ const url = loopbackUrl(pv);
396
500
  const shots = pv && /!\[[^\]]*\]\(/.test(pv);
397
501
  if (url && loopback && !shots) return void el.insertAdjacentHTML("beforeend", String(html`<iframe class="rframe" title="Preview" src="${url}"></iframe>`));
398
502
  const bar = url ? html`<div class="urlbar"><span class="sel">${url}</span>${winBtn(url)}</div>` : "";
@@ -436,14 +540,14 @@ const openPreview = () => addTab({ id: "preview", kind: "preview", title: "Previ
436
540
 
437
541
  // The run's recorded session, resumed in a board terminal tied to it. While it still runs in
438
542
  // another terminal the server says so (409 live) and a tab explains; with no session, a shell.
439
- async function openAgent(again = false) {
440
- const k = runKey(card);
441
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: card.state, run: k, resume: true }) }).catch(() => null);
543
+ async function openAgent(c, again = false, focus = true) {
544
+ const k = key(c);
545
+ const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: c.state, ws: ctx!.ws, run: k, resume: true }) }).catch(() => null);
442
546
  if (r?.ok) {
443
547
  elsewhere.delete(k);
444
548
  const sh = await r.json();
445
549
  shells.push(sh);
446
- return show("sh:" + sh.key);
550
+ return focus ? show("sh:" + sh.key) : draw();
447
551
  }
448
552
  const j: any = r ? await r.json().catch(() => ({})) : {};
449
553
  if (r?.status === 409 && j.live) {
@@ -453,12 +557,11 @@ async function openAgent(again = false) {
453
557
  }
454
558
  elsewhere.delete(k);
455
559
  if (again) toast(j.error || "Could not resume the session");
456
- else if (!tabs().length) void newPty();
457
560
  else draw();
458
561
  }
459
562
 
460
563
  async function newPty(agent?: string) {
461
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: card.state, run: runKey(card), ...(agent ? { agent } : {}) }) });
564
+ const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: ctx!.dir, ws: ctx!.ws, run: ctx!.k, ...(agent ? { agent } : {}) }) });
462
565
  if (r.status === 501) {
463
566
  noPty = true;
464
567
  return draw();
@@ -483,7 +586,7 @@ async function closeTab(id: string) {
483
586
  await post("/pty/exit", { key: id.slice(3) });
484
587
  shells = shells.filter((x) => "sh:" + x.key !== id);
485
588
  } else if (id.startsWith("agent:")) s.hidden.push(id);
486
- else if (id === "wait") elsewhere.delete(runKey(card));
589
+ else if (id.startsWith("wait:")) elsewhere.delete(id.slice(5));
487
590
  else s.tabs = s.tabs.filter((t) => t.id !== id);
488
591
  save();
489
592
  draw();
@@ -533,14 +636,15 @@ function wire() {
533
636
  target = mode === "tab" || !s.on ? null : { screen: s.on, dir: mode as "cols" | "rows" };
534
637
  if (n === "shell") void newPty();
535
638
  else if (n.startsWith("agent:")) void newPty(n.slice(6));
536
- else if (n === "local") addTab({ id: "local", kind: "local", title: "localhost" });
639
+ else if (n === "local") addTab({ id: "local", kind: "local", title: "Browser" });
640
+ else if (n === "history") addTab({ id: "history", kind: "history", title: "History" });
537
641
  else openPreview();
538
642
  return;
539
643
  }
540
- if (t.closest("#rside")) {
541
- document.body.classList.toggle("rflip");
542
- draw();
543
- }
644
+ };
645
+ $("rside").onclick = () => {
646
+ document.body.classList.toggle("rflip");
647
+ draw();
544
648
  };
545
649
  // The +, split right and split down menus open under their button, kept inside the
546
650
  // centre panel; one open at a time. A pane's own × closes just that item.
@@ -558,7 +662,10 @@ function wire() {
558
662
  $("rpanes").onclick = (e) => {
559
663
  const x = (e.target as HTMLElement).closest<HTMLElement>(".ph [data-x]")?.dataset.x;
560
664
  if (x) return void closeTab(x);
561
- if ((e.target as HTMLElement).closest("[data-b=recheck]")) return void openAgent(true);
665
+ const rk = (e.target as HTMLElement).closest<HTMLElement>("[data-b=recheck]")?.dataset.k;
666
+ if (rk && byKey(rk)) return void openAgent(byKey(rk), true);
667
+ const hist = (e.target as HTMLElement).closest<HTMLElement>("[data-hist]")?.dataset.hist;
668
+ if (hist && byKey(hist)) return pickRun(hist);
562
669
  const mv = (e.target as HTMLElement).closest<HTMLElement>("[data-mv]");
563
670
  if (mv) {
564
671
  const id = mv.closest<HTMLElement>(".rpane")!.dataset.t!;
@@ -578,6 +685,14 @@ function wire() {
578
685
  e.dataTransfer!.setData("text/plain", id);
579
686
  e.dataTransfer!.effectAllowed = "move";
580
687
  };
688
+ // A tab is the handle too: dragging it moves its focused pane (the only one, unsplit).
689
+ bar.ondragstart = (e) => {
690
+ const sc = saved().screens.find((x) => x.id === (e.target as HTMLElement).closest<HTMLElement>(".rtab")?.dataset.t);
691
+ if (!sc) return;
692
+ dragging = leaves(sc.tree).includes(sc.focus) ? sc.focus : leaves(sc.tree)[0];
693
+ e.dataTransfer!.setData("text/plain", dragging);
694
+ e.dataTransfer!.effectAllowed = "move";
695
+ };
581
696
  box.ondragend = bar.ondragend = () => {
582
697
  dragging = null;
583
698
  document.querySelectorAll(".rdrop,.rdrop-l,.rdrop-r,.rdrop-t,.rdrop-b").forEach((x) => x.classList.remove("rdrop", "rdrop-l", "rdrop-r", "rdrop-t", "rdrop-b"));
@@ -634,13 +749,14 @@ function wire() {
634
749
 
635
750
  // Leaving the workspace: its terminals unmount; the shells keep running on the server.
636
751
  function stopPanes() {
752
+ $("panel").classList.add("parked");
637
753
  for (const p of panes.values()) p.off?.();
638
754
  panes.clear();
639
755
  $("rpanes").innerHTML = "";
640
756
  }
641
757
  export function runStop() {
642
758
  stopPanes();
643
- card = null;
759
+ card = ctx = null;
644
760
  $("panel").classList.remove("pn");
645
761
  }
646
762
 
@@ -651,7 +767,7 @@ async function projectNotes() {
651
767
  const box = $("pnlist");
652
768
  box.innerHTML = "";
653
769
  try {
654
- const d = await (await fetch("/vault?dir=" + encodeURIComponent(card.state))).json();
770
+ const d = await (await fetch("/vault?dir=" + encodeURIComponent(ctx!.dir))).json();
655
771
  const names: string[] = (d.notes ?? []).map((n) => n.name).sort();
656
772
  // Folders first-level as headings, notes under them: "Project/Web board" shows under Project.
657
773
  const groups = new Map<string, string[]>();
@@ -669,6 +785,34 @@ async function projectNotes() {
669
785
  }
670
786
  }
671
787
 
788
+ // The keys of the workspace's runs that were at review/done on the last tick, per workspace.
789
+ const was = new Map<string, Set<string>>();
790
+ // A run in the open workspace moves into review or done with a localhost address in its ## Preview:
791
+ // the Browser opens on it, once per run. The first tick of a workspace only records.
792
+ const mineNow = () => store.S.cards.filter((c) => c.state === ctx!.dir && wsOfCard(c) === ctx!.ws);
793
+ async function autoBrowse() {
794
+ if (!ctx) return;
795
+ const k = ctx.k,
796
+ mine = mineNow(),
797
+ prev = was.get(k);
798
+ was.set(k, new Set(mine.filter(reviewing).map(key)));
799
+ if (!prev) return;
800
+ for (const c of toOpen(mine, prev, saved().seen ?? [], key)) {
801
+ let u: string | undefined;
802
+ try {
803
+ const doc = await (await fetch(`/run/${encodeURIComponent(c.id)}?dir=${encodeURIComponent(c.state)}`)).json();
804
+ u = loopbackUrl(preview(doc.impl));
805
+ } catch {}
806
+ if (!u || ctx?.k !== k || saved().seen?.includes(key(c))) continue;
807
+ (saved().seen ||= []).push(key(c));
808
+ try {
809
+ localStorage.setItem("kz-browse:" + k, u);
810
+ } catch {}
811
+ addTab({ id: "local", kind: "local", title: "Browser" });
812
+ (panes.get("local")?.el as any)?.browseTo?.(u);
813
+ }
814
+ }
815
+
672
816
  export function initRunView() {
673
817
  // A phone's sheet closes with the panel's ×, which here hides the sheet rather than closing the card.
674
818
  document.addEventListener(
@@ -677,9 +821,21 @@ export function initRunView() {
677
821
  if (!document.body.classList.contains("runv") || !(e.target as Element).closest?.("#pclose")) return;
678
822
  e.stopPropagation();
679
823
  document.body.classList.remove("rflip");
824
+ setOpen(false);
680
825
  },
681
826
  true,
682
827
  );
828
+ initPick(pickRun);
829
+ // The sidebar's agent mark: open that workspace with the agent's terminal tab selected.
830
+ addEventListener("kz-open-term", (e: any) => {
831
+ e.preventDefault();
832
+ const { dir, ws, key } = e.detail;
833
+ wantTerm = key;
834
+ if (ctx?.k === wsKey(dir, ws) && document.body.classList.contains("runv")) return void showTerm();
835
+ history.pushState(null, "", wsHref(dir, ws));
836
+ markCurrent();
837
+ go("ws");
838
+ });
683
839
  addEventListener("kz-run-preview", openPreview);
684
840
  $("pnotes").onclick = () => void projectNotes();
685
841
  $("pnlist").onclick = (e) => {
@@ -688,7 +844,8 @@ export function initRunView() {
688
844
  };
689
845
  // A /state change: new or ended sessions, the card's own state. Panes stay mounted.
690
846
  addEventListener("kz-state", () => {
691
- if (card && document.body.classList.contains("runv")) void showRunView();
847
+ void autoBrowse();
848
+ if (ctx && document.body.classList.contains("runv")) void showRunView();
692
849
  });
693
850
  }
694
851
  // Opens a card's workspace, its address in the history.