kaizen-agent 1.59.2 → 1.60.1

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 (63) 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 +89 -5
  9. package/cli/pty.ts +126 -9
  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-pr.test.ts +51 -0
  18. package/cli/web-symlink.test.ts +28 -0
  19. package/cli/web.ts +349 -100
  20. package/cli/worktree.test.ts +146 -1
  21. package/cli/worktree.ts +214 -4
  22. package/cli/writeback.ts +1 -1
  23. package/package.json +1 -1
  24. package/skills/kaizen/SKILL.md +5 -1
  25. package/skills/kaizen/config.default.yml +15 -2
  26. package/skills/kaizen/settings.md +1 -0
  27. package/skills/kaizen/spec-main.md +28 -2
  28. package/skills/kaizen-help/SKILL.md +1 -0
  29. package/web/board/add-project.ts +136 -0
  30. package/web/board/api.ts +1 -1
  31. package/web/board/badge.ts +5 -5
  32. package/web/board/cards.ts +11 -3
  33. package/web/board/context.ts +1 -0
  34. package/web/board/fixes.ts +3 -2
  35. package/web/board/git.ts +309 -60
  36. package/web/board/home.ts +7 -1
  37. package/web/board/ideas.ts +20 -3
  38. package/web/board/live.ts +1 -1
  39. package/web/board/main.ts +26 -9
  40. package/web/board/panel.ts +31 -16
  41. package/web/board/projects.ts +6 -85
  42. package/web/board/run-pick.ts +41 -0
  43. package/web/board/run-view.ts +286 -110
  44. package/web/board/search-match.ts +20 -0
  45. package/web/board/search.test.ts +20 -0
  46. package/web/board/search.ts +324 -0
  47. package/web/board/settings.ts +42 -5
  48. package/web/board/store.ts +3 -1
  49. package/web/board/toast.ts +4 -1
  50. package/web/board/views.ts +3 -1
  51. package/web/board/workspace.ts +127 -38
  52. package/web/board/ws-board-ui.ts +95 -0
  53. package/web/board/ws-board.test.ts +71 -0
  54. package/web/board/ws-board.ts +45 -0
  55. package/web/board/ws-tabs.test.ts +181 -0
  56. package/web/board/ws-tabs.ts +173 -0
  57. package/web/board.html +86 -36
  58. package/web/board.js +129 -44
  59. package/web/notebook.js +41 -24
  60. package/web/notes.html +26 -20
  61. package/web/term.js +1 -1
  62. package/web/video.html +26 -20
  63. package/web/video.js +76 -59
@@ -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, titleOf } from "./workspace.ts";
21
+ import { cardHref, markCurrent, railData, stateOf, 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
  };
@@ -74,9 +76,13 @@ let target: { screen: string; dir: "cols" | "rows" } | null = null;
74
76
  function screens(): Screen[] {
75
77
  const s = saved(),
76
78
  ids = tabs().map((t) => t.id);
77
- s.screens = s.screens.flatMap((sc) => {
79
+ // In place: the panes on screen hold these objects, and a gutter drag writes its sizes into them.
80
+ s.screens = s.screens.filter((sc) => {
78
81
  const tree = prune(sc.tree, (id) => ids.includes(id));
79
- return tree ? [{ ...sc, tree, focus: leaves(tree).includes(sc.focus) ? sc.focus : leaves(tree)[0] }] : [];
82
+ if (!tree) return false;
83
+ sc.tree = tree;
84
+ if (!leaves(tree).includes(sc.focus)) sc.focus = leaves(tree)[0];
85
+ return true;
80
86
  });
81
87
  for (const id of ids)
82
88
  if (!s.screens.some((sc) => leaves(sc.tree).includes(id))) {
@@ -90,70 +96,121 @@ function screens(): Screen[] {
90
96
  }
91
97
  const loopback = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname);
92
98
 
99
+ const AGENTS = ["claude", "codex", "gemini", "agy", "opencode", "cursor"];
100
+ const wsCards = () => (ctx ? liveIn(store.S.cards, ctx.dir, ctx.ws, wsOfCard) : []);
101
+
93
102
  function tabs(): Tab[] {
94
103
  const s = saved(),
95
104
  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
105
  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];
106
+ const live = wsCards(),
107
+ liveKeys = new Set(live.map(key));
108
+ // Each live run's terminals: its stage terminals ("Build · Claude"), other sessions, shells, the waiting note.
109
+ for (const c of live) {
110
+ const k = key(c),
111
+ runAgent = AGENTS.find((a) => c.tags?.includes(a)) ?? undefined;
112
+ for (const t of stageTabs(c, named(runAgent))) out.push({ id: "agent:" + t.key, kind: "agent", agent: runAgent, title: t.title, key: t.key });
113
+ 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 });
114
+ // The run's own session is running in another terminal: a tab that says so.
115
+ if (elsewhere.has(k)) out.push({ id: "wait:" + k, kind: "wait", agent: "claude", title: named("claude") });
116
+ }
117
+ // The workspace's own shells and agents, and those of its finished runs.
118
+ const owned = new Set(store.S.cards.filter((c) => c.state === ctx!.dir && wsOfCard(c) === ctx!.ws).map(key));
119
+ for (const sh of shells.filter((x) => x.run === ctx!.k || (owned.has(x.run) && !liveKeys.has(x.run))))
120
+ out.push({ id: "sh:" + sh.key, kind: sh.agent ? "agent" : "shell", agent: sh.agent || undefined, title: sh.title, key: sh.key });
121
+ // Opened by hand: History, localhost, Preview, notes.
122
+ const mine = s.tabs.map((t) => (t.kind === "local" ? { ...t, title: "Browser" } : t)); // "local" was saved before the rename
123
+ const all = [...out.filter((t) => !s.hidden.includes(t.id)), ...mine];
124
+ return all.filter((t, i) => all.findIndex((x) => x.id === t.id) === i);
105
125
  }
106
126
  // 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]));
127
+ const icon = (t: Tab) =>
128
+ 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
129
  const elsewhere = new Set<string>();
109
130
 
131
+ let switched: string | null = null; // the project a deep link last switched the board to
132
+ const none = (t: string) => void ($("rtabs").innerHTML = String(html`<span class="rnone">${t}</span>`));
110
133
  // Called by go("run") and on every /state: draws the tab strip and keeps the panes.
111
- export async function showRunView() {
134
+ export async function showRunView(nav = false) {
112
135
  const p = new URLSearchParams(location.search),
113
136
  dir = p.get("dir"),
114
137
  id = p.get("id"),
115
138
  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;
139
+ let ws = p.get("ws"),
140
+ want: any = null; // the card the address names, whose tab is selected
141
+ // A project this board is not showing: a deep link names its project, switched to once, as a rail click does.
142
+ const away = async () => {
143
+ if (store.all || !dir || dir === store.dir || dir === switched) return false;
144
+ switched = dir;
145
+ await pick(dir).catch(() => {});
146
+ return true;
147
+ };
148
+ if (p.get("view") === "ws" && ws) {
149
+ if (await away()) return showRunView(nav);
150
+ } else {
151
+ const find = (cs) => cs.find((x) => x.state === dir && (id ? x.kind === "run" && x.id === id : x.kind === "idea" && x.text === idea));
152
+ const c = find(store.S.cards);
153
+ // A launched idea becomes a run: its agent session moves to the run's card, and the view follows.
154
+ const pk = idea && (c ?? card)?.kind === "idea" && (c ?? card)?.pty?.key;
155
+ const run = pk && store.S.cards.find((x) => x.kind === "run" && x.state === dir && (x.pty?.key === pk || x.pty?.all?.includes(pk)));
156
+ if (run) {
157
+ history.replaceState(null, "", cardHref(run));
158
+ markCurrent();
159
+ return showRunView(nav);
160
+ }
161
+ if (!c) {
162
+ if (await away()) return showRunView(nav);
163
+ if (!store.all && find(railData().cards)) location.href = "/?all=1&" + p.toString();
164
+ else (stopPanes(), (ctx = card = null), none(`That ${id ? "run" : "idea"} is not on this board.`));
165
+ return;
166
+ }
167
+ want = c;
168
+ ws = wsOfCard(c);
131
169
  }
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
- // A phone titles the workspace with the run, in the page header.
137
- document.querySelector(".hdr h1")!.textContent = titleOf(c);
138
- if (fresh || store.openKey !== key(c)) open(c);
170
+ if (!dir || !ws) return void (stopPanes(), (ctx = card = null), none("That workspace is not on this board."));
171
+ const k = wsKey(dir, ws);
172
+ const fresh = ctx?.k !== k;
173
+ // Each workspace has its own centre: switching unmounts this one's panes (its shells keep running on the server).
174
+ if (fresh) (stopPanes(), (card = null), (ctx = { dir, ws, k }));
175
+ 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
176
+ // The header titles a phone's workspace: the run, else the branch.
177
+ const w = railData().projects?.find((x) => x.dir === dir)?.workspaces?.find((x) => x.path === ws);
178
+ document.querySelector(".hdr h1")!.textContent = want ? titleOf(want) : w?.branch || ws.split(/[\\/]/).pop() || "Workspace";
179
+ // Layouts saved per run before workspaces move to their workspace; keys no card owns stay.
180
+ if (migrate(ALL, store.S.cards, key, wsOfCard)) save();
139
181
  try {
140
- const r = await fetch("/shells?dir=" + encodeURIComponent(c.state));
182
+ const r = await fetch("/shells?dir=" + encodeURIComponent(dir));
141
183
  shells = r.ok ? await r.json() : [];
142
184
  } catch {}
143
185
  if (fresh) {
144
186
  try {
145
- agents = (await (await fetch("/agents?dir=" + encodeURIComponent(c.state))).json()).agents ?? [];
187
+ const d = await (await fetch("/agents?dir=" + encodeURIComponent(dir))).json();
188
+ agents = d.agents ?? [];
189
+ defAgent = d.default ?? "";
146
190
  } catch {}
147
191
  }
148
- if (card !== c) return;
149
- // Nothing to show (no board-launched agent, no shell, no tab saved): the run's own Claude
150
- // session resumed here, else a shell in the project, once per run per visit, so the centre
151
- // is never blank. Only the run's recorded session is ever resumed; nothing new is started.
152
- if (!tabs().length && !noPty && !autoShell.has(runKey(c))) {
153
- autoShell.add(runKey(c));
154
- return void (c.kind === "run" ? openAgent() : newPty());
192
+ if (ctx?.k !== k) return;
193
+ // 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.
194
+ // A fresh visit forgets the old pick (waiting first again); one made during the visit stays.
195
+ if (fresh) picked.delete(k);
196
+ if (want?.kind === "run" && (nav || fresh)) picked.set(k, key(want));
197
+ // A workspace with nothing open starts a shell in its folder (no agent, no run). A live run whose own Claude
198
+ // session is not open anywhere on the board is resumed here, once per visit.
199
+ if (!noPty) {
200
+ if (!tabs().length && !autoShell.has(k)) return void (autoShell.add(k), newPty());
201
+ if (want && want.kind === "run" && !finished(want) && !want.pty && !shells.some((x) => x.run === key(want)) && !autoShell.has(key(want))) {
202
+ autoShell.add(key(want));
203
+ void openAgent(want, false, false);
204
+ }
155
205
  }
156
- draw();
206
+ if (!showTerm()) draw();
207
+ }
208
+ // The terminal the sidebar asked for, selected once the workspace's tabs are known.
209
+ let wantTerm: string | null = null;
210
+ function showTerm() {
211
+ const t = wantTerm && tabs().find((x) => x.key === wantTerm);
212
+ wantTerm = null;
213
+ return !!t && (show(t.id), true);
157
214
  }
158
215
  const autoShell = new Set<string>();
159
216
 
@@ -164,15 +221,18 @@ function draw() {
164
221
  cur = scs.find((sc) => sc.id === s.on);
165
222
  const item = (id: string) => ts.find((t) => t.id === id)!;
166
223
  const PTY = !noPty;
167
- 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>`;
224
+ const mark = (a) => (MARKS.includes(a.cmd) ? raw(`<svg><use href="#i-${a.cmd}"/></svg>`) : ico("ai"));
225
+ const dflt = agents.find((a) => a.cmd === defAgent);
226
+ 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>`;
168
227
  $("rtabs").innerHTML = String(
169
228
  html`${scs.map((sc) => {
170
229
  const ids = leaves(sc.tree),
171
230
  first = item(ids[0]),
172
231
  title = ids.map((id) => item(id).title).join(" + ");
173
- 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>`;
174
- })}<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>`,
232
+ 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>`;
233
+ })}<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>` : ""}`,
175
234
  );
235
+ $("rside").setAttribute("aria-pressed", String(document.body.classList.contains("rflip")));
176
236
  $("rtabs").querySelector(".rtab.on")?.scrollIntoView({ block: "nearest", inline: "nearest" });
177
237
  // Panes: made once per item, kept (hidden) while it is open, so terminals never reconnect.
178
238
  const box = $("rpanes");
@@ -189,6 +249,7 @@ function draw() {
189
249
  p.el.classList.toggle("split", shown.length > 1);
190
250
  p.el.classList.toggle("focus", shown.length > 1 && id === cur?.focus);
191
251
  p.el.querySelector(".ph span")!.textContent = item(id)?.title ?? "";
252
+ if (item(id)?.kind === "history") fillHistory(p.el);
192
253
  }
193
254
  // The tree is rebuilt only when it changes: moving a pane in the DOM reloads its frame.
194
255
  const sig = cur ? cur.id + JSON.stringify(cur.tree) : "";
@@ -200,10 +261,47 @@ function draw() {
200
261
  }
201
262
  // One empty note at most: every draw used to append another.
202
263
  box.querySelector(".rempty")?.remove();
203
- 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>`));
264
+ 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>`));
265
+ mountPanel();
204
266
  wire();
205
267
  }
206
268
 
269
+ // The run panel (#panel) stays docked on the right of the centre and shows one run: the one picked
270
+ // in its header (run-pick.ts), first the run waiting on you, else the newest. A pick is sticky; a
271
+ // run that starts waiting later does not replace it: the picker's trigger and, with the panel
272
+ // collapsed, the panel button show a dot. With no run the panel is parked.
273
+ const picked = new Map<string, string>();
274
+ let pickOpen = false;
275
+ // Shows a run in the panel (a picker row, a History row); the centre stays as it is.
276
+ const pickRun = (k: string) => (picked.set(ctx!.k, k), draw()); // the sidebar count asked for the picker dropped down
277
+ function mountPanel() {
278
+ const live = pickable(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
279
+ hist = historyOf(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
280
+ c = chosen(live, hist, picked.get(ctx!.k), key);
281
+ $("panel").classList.toggle("parked", !c);
282
+ $("rside").hidden = !c;
283
+ // Collapsed (a phone: sheet down) and a run waits: a dot on the panel button, no pop-open.
284
+ $("rside").toggleAttribute("data-dot", document.body.classList.contains("rflip") !== isPhone() && live.some(awaiting));
285
+ if (!c) return void ((card = null), (pickOpen = false), hidePick());
286
+ picked.set(ctx!.k, key(c));
287
+ $("panel").classList.toggle("ro", hist.includes(c)); // a run from History: no edit buttons (the commit and push ones stay)
288
+ card = c;
289
+ drawPick(live, hist, c);
290
+ if (store.openKey !== key(c)) void open(c, false);
291
+ if (pickOpen) (setOpen(true), (pickOpen = false));
292
+ }
293
+ // History: the workspace's finished runs, newest first; one opens read-only.
294
+ function fillHistory(el: HTMLElement) {
295
+ const list = historyOf(store.S.cards, ctx!.dir, ctx!.ws, wsOfCard),
296
+ now = Date.now();
297
+ const box = el.querySelector(".rhist")!;
298
+ box.innerHTML = String(
299
+ list.length
300
+ ? 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>`)}`
301
+ : html`<p class="rnone">No finished runs in this workspace yet.</p>`,
302
+ );
303
+ }
304
+
207
305
  let shownSig = "";
208
306
  // Moves an item out of its tab into another one (split beside a pane there, or next to its
209
307
  // focused pane), or into a tab of its own (to = null). Terminals keep running; frames reload.
@@ -252,6 +350,8 @@ function build(n: Node, sc: Screen): HTMLElement {
252
350
  sum = n.sizes[i - 1] + n.sizes[i],
253
351
  start = horiz ? ra.left : ra.top;
254
352
  g.setPointerCapture(e.pointerId);
353
+ // A frame under the pointer (the Browser, Preview) takes the moves for itself: frames ignore it while dragging.
354
+ document.body.classList.add("rdrag");
255
355
  g.onpointermove = (m) => {
256
356
  const f = Math.min(0.9, Math.max(0.1, ((horiz ? m.clientX : m.clientY) - start) / total));
257
357
  n.sizes[i - 1] = sum * f;
@@ -259,8 +359,10 @@ function build(n: Node, sc: Screen): HTMLElement {
259
359
  a.style.flexGrow = String(n.sizes[i - 1]);
260
360
  b.style.flexGrow = String(n.sizes[i]);
261
361
  };
262
- g.onpointerup = () => {
263
- g.onpointermove = g.onpointerup = null;
362
+ g.onpointerup = g.onlostpointercapture = () => {
363
+ if (!g.onpointermove) return;
364
+ document.body.classList.remove("rdrag");
365
+ g.onpointermove = g.onpointerup = g.onlostpointercapture = null;
264
366
  shownSig = sc.id + JSON.stringify(sc.tree);
265
367
  save();
266
368
  };
@@ -284,7 +386,10 @@ function makePane(t: Tab) {
284
386
  const p = { el, off: null as null | (() => void) };
285
387
  panes.set(t.id, p);
286
388
  $("rpanes").append(el);
287
- if (t.kind === "agent" || t.kind === "shell") {
389
+ if (t.kind === "history") {
390
+ el.insertAdjacentHTML("beforeend", String(html`<div class="rhist md"></div>`));
391
+ fillHistory(el);
392
+ } else if (t.kind === "agent" || t.kind === "shell") {
288
393
  const term = document.createElement("div");
289
394
  term.className = "term";
290
395
  el.append(term);
@@ -296,16 +401,17 @@ function makePane(t: Tab) {
296
401
  } else if (t.kind === "wait")
297
402
  el.insertAdjacentHTML(
298
403
  "beforeend",
299
- 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>`),
404
+ 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>`),
300
405
  );
301
406
  else if (t.kind === "local") browser(el);
302
- 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>`));
407
+ 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>`));
303
408
  else void previewPane(el);
304
409
  }
305
410
 
306
- // The localhost tab: a URL bar over an iframe. The URL is kept per project.
411
+ // The Browser tab: a URL bar over an iframe. The address is kept per workspace; a run's
412
+ // Preview sets it when the run reaches review (autoBrowse).
307
413
  function browser(el: HTMLElement) {
308
- const k = "kz-browse:" + card.state;
414
+ const k = "kz-browse:" + ctx!.k;
309
415
  let url = "http://localhost:3000";
310
416
  try {
311
417
  url = localStorage.getItem(k) || url;
@@ -314,16 +420,19 @@ function browser(el: HTMLElement) {
314
420
  fwd: string[] = [];
315
421
  el.insertAdjacentHTML(
316
422
  "beforeend",
317
- 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>`),
423
+ 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>`),
318
424
  );
319
425
  const f = el.querySelector("form")!,
320
426
  inp = f.querySelector("input")!,
321
427
  ext = f.querySelector<HTMLAnchorElement>("a.rwin");
428
+ (el as any).browseTo = (u: string) => go(u);
322
429
  // On a phone over the tailnet, localhost is the phone itself: framing it shows nothing useful.
323
430
  const local = (u) => /^https?:\/\/(localhost|127\.0\.0\.1|\[::1\])(:|\/|$)/.test(u);
324
431
  const frame = document.createElement("iframe");
325
432
  frame.className = "rframe";
326
- frame.title = "localhost";
433
+ frame.title = "Browser";
434
+ // Dev apps run; a framed page cannot navigate the board itself (no allow-top-navigation).
435
+ frame.setAttribute("sandbox", "allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-modals allow-downloads");
327
436
  const note = document.createElement("p");
328
437
  note.className = "rnote";
329
438
  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.";
@@ -351,8 +460,9 @@ function browser(el: HTMLElement) {
351
460
  frame.hidden = true;
352
461
  frame.removeAttribute("src");
353
462
  note.hidden = false;
354
- note.textContent = `${new URL(u).host} does not allow being shown inside another page. `;
355
- note.insertAdjacentHTML("beforeend", String(winBtn(u)));
463
+ // The fallback card: the page refuses to be framed, so offer it outside the board.
464
+ note.textContent = "";
465
+ 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)}`));
356
466
  })
357
467
  .catch(() => {});
358
468
  };
@@ -374,11 +484,11 @@ function browser(el: HTMLElement) {
374
484
 
375
485
  // A Chromium app window on the board's computer (POST /open-url): for dev servers that
376
486
  // refuse to be framed. Only offered when the page itself is on that computer.
377
- // One labelled button: on the board's computer a Chromium app window, elsewhere a new tab.
487
+ // One labelled button: a Chromium app window on the board's computer, for loopback pages only.
378
488
  const winBtn = (u: string) =>
379
- loopback
380
- ? html`<button type="button" class="rwin" data-b="win" title="Open in a browser window">${ico("popout")}<span>Open in browser</span></button>`
381
- : html`<a class="rwin" target="_blank" rel="noopener" href="${u}">${ico("popout")}<span>Open in browser</span></a>`;
489
+ loopback && loopbackUrl(u)
490
+ ? html`<button type="button" class="rwin" data-b="win" title="Open in an app window">${ico("popout")}<span>Open in app window</span></button>`
491
+ : "";
382
492
  async function openWindow(u: string) {
383
493
  const r = await fetch("/open-url", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ url: u }) }).catch(() => null);
384
494
  if (!r?.ok) toast("Could not open a browser window" + (r ? ": " + ((await r.json().catch(() => ({}))) as any).error : ""));
@@ -388,13 +498,13 @@ async function openWindow(u: string) {
388
498
  // app link when it names a localhost address. The address is framed only when the Preview
389
499
  // has no images: the dev server a run used is often gone, and a dead frame hides the proof.
390
500
  async function previewPane(el: HTMLElement) {
391
- let doc = store.runDoc && store.runDoc.id === card.id ? store.runDoc : null;
392
- if (!doc && card.kind === "run")
501
+ let doc = store.runDoc && store.runDoc.id === card?.id ? store.runDoc : null;
502
+ if (!doc && card?.kind === "run")
393
503
  try {
394
504
  doc = await (await fetch(`/run/${encodeURIComponent(card.id)}?dir=${encodeURIComponent(card.state)}`)).json();
395
505
  } catch {}
396
506
  const pv = doc && preview(doc.impl);
397
- const url = pv && /https?:\/\/(?:localhost|127\.0\.0\.1)(?::\d+)?[^\s)`'"<>]*/.exec(pv)?.[0];
507
+ const url = loopbackUrl(pv);
398
508
  const shots = pv && /!\[[^\]]*\]\(/.test(pv);
399
509
  if (url && loopback && !shots) return void el.insertAdjacentHTML("beforeend", String(html`<iframe class="rframe" title="Preview" src="${url}"></iframe>`));
400
510
  const bar = url ? html`<div class="urlbar"><span class="sel">${url}</span>${winBtn(url)}</div>` : "";
@@ -438,14 +548,14 @@ const openPreview = () => addTab({ id: "preview", kind: "preview", title: "Previ
438
548
 
439
549
  // The run's recorded session, resumed in a board terminal tied to it. While it still runs in
440
550
  // another terminal the server says so (409 live) and a tab explains; with no session, a shell.
441
- async function openAgent(again = false) {
442
- const k = runKey(card);
443
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: card.state, run: k, resume: true }) }).catch(() => null);
551
+ async function openAgent(c, again = false, focus = true) {
552
+ const k = key(c);
553
+ 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);
444
554
  if (r?.ok) {
445
555
  elsewhere.delete(k);
446
556
  const sh = await r.json();
447
557
  shells.push(sh);
448
- return show("sh:" + sh.key);
558
+ return focus ? show("sh:" + sh.key) : draw();
449
559
  }
450
560
  const j: any = r ? await r.json().catch(() => ({})) : {};
451
561
  if (r?.status === 409 && j.live) {
@@ -455,12 +565,11 @@ async function openAgent(again = false) {
455
565
  }
456
566
  elsewhere.delete(k);
457
567
  if (again) toast(j.error || "Could not resume the session");
458
- else if (!tabs().length) void newPty();
459
568
  else draw();
460
569
  }
461
570
 
462
571
  async function newPty(agent?: string) {
463
- const r = await fetch("/shell", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dir: card.state, run: runKey(card), ...(agent ? { agent } : {}) }) });
572
+ 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 } : {}) }) });
464
573
  if (r.status === 501) {
465
574
  noPty = true;
466
575
  return draw();
@@ -485,7 +594,7 @@ async function closeTab(id: string) {
485
594
  await post("/pty/exit", { key: id.slice(3) });
486
595
  shells = shells.filter((x) => "sh:" + x.key !== id);
487
596
  } else if (id.startsWith("agent:")) s.hidden.push(id);
488
- else if (id === "wait") elsewhere.delete(runKey(card));
597
+ else if (id.startsWith("wait:")) elsewhere.delete(id.slice(5));
489
598
  else s.tabs = s.tabs.filter((t) => t.id !== id);
490
599
  save();
491
600
  draw();
@@ -535,14 +644,15 @@ function wire() {
535
644
  target = mode === "tab" || !s.on ? null : { screen: s.on, dir: mode as "cols" | "rows" };
536
645
  if (n === "shell") void newPty();
537
646
  else if (n.startsWith("agent:")) void newPty(n.slice(6));
538
- else if (n === "local") addTab({ id: "local", kind: "local", title: "localhost" });
647
+ else if (n === "local") addTab({ id: "local", kind: "local", title: "Browser" });
648
+ else if (n === "history") addTab({ id: "history", kind: "history", title: "History" });
539
649
  else openPreview();
540
650
  return;
541
651
  }
542
- if (t.closest("#rside")) {
543
- document.body.classList.toggle("rflip");
544
- draw();
545
- }
652
+ };
653
+ $("rside").onclick = () => {
654
+ document.body.classList.toggle("rflip");
655
+ draw();
546
656
  };
547
657
  // The +, split right and split down menus open under their button, kept inside the
548
658
  // centre panel; one open at a time. A pane's own × closes just that item.
@@ -560,7 +670,10 @@ function wire() {
560
670
  $("rpanes").onclick = (e) => {
561
671
  const x = (e.target as HTMLElement).closest<HTMLElement>(".ph [data-x]")?.dataset.x;
562
672
  if (x) return void closeTab(x);
563
- if ((e.target as HTMLElement).closest("[data-b=recheck]")) return void openAgent(true);
673
+ const rk = (e.target as HTMLElement).closest<HTMLElement>("[data-b=recheck]")?.dataset.k;
674
+ if (rk && byKey(rk)) return void openAgent(byKey(rk), true);
675
+ const hist = (e.target as HTMLElement).closest<HTMLElement>("[data-hist]")?.dataset.hist;
676
+ if (hist && byKey(hist)) return pickRun(hist);
564
677
  const mv = (e.target as HTMLElement).closest<HTMLElement>("[data-mv]");
565
678
  if (mv) {
566
679
  const id = mv.closest<HTMLElement>(".rpane")!.dataset.t!;
@@ -580,6 +693,14 @@ function wire() {
580
693
  e.dataTransfer!.setData("text/plain", id);
581
694
  e.dataTransfer!.effectAllowed = "move";
582
695
  };
696
+ // A tab is the handle too: dragging it moves its focused pane (the only one, unsplit).
697
+ bar.ondragstart = (e) => {
698
+ const sc = saved().screens.find((x) => x.id === (e.target as HTMLElement).closest<HTMLElement>(".rtab")?.dataset.t);
699
+ if (!sc) return;
700
+ dragging = leaves(sc.tree).includes(sc.focus) ? sc.focus : leaves(sc.tree)[0];
701
+ e.dataTransfer!.setData("text/plain", dragging);
702
+ e.dataTransfer!.effectAllowed = "move";
703
+ };
583
704
  box.ondragend = bar.ondragend = () => {
584
705
  dragging = null;
585
706
  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"));
@@ -636,13 +757,14 @@ function wire() {
636
757
 
637
758
  // Leaving the workspace: its terminals unmount; the shells keep running on the server.
638
759
  function stopPanes() {
760
+ $("panel").classList.add("parked");
639
761
  for (const p of panes.values()) p.off?.();
640
762
  panes.clear();
641
763
  $("rpanes").innerHTML = "";
642
764
  }
643
765
  export function runStop() {
644
766
  stopPanes();
645
- card = null;
767
+ card = ctx = null;
646
768
  $("panel").classList.remove("pn");
647
769
  }
648
770
 
@@ -653,7 +775,7 @@ async function projectNotes() {
653
775
  const box = $("pnlist");
654
776
  box.innerHTML = "";
655
777
  try {
656
- const d = await (await fetch("/vault?dir=" + encodeURIComponent(card.state))).json();
778
+ const d = await (await fetch("/vault?dir=" + encodeURIComponent(ctx!.dir))).json();
657
779
  const names: string[] = (d.notes ?? []).map((n) => n.name).sort();
658
780
  // Folders first-level as headings, notes under them: "Project/Web board" shows under Project.
659
781
  const groups = new Map<string, string[]>();
@@ -671,6 +793,34 @@ async function projectNotes() {
671
793
  }
672
794
  }
673
795
 
796
+ // The keys of the workspace's runs that were at review/done on the last tick, per workspace.
797
+ const was = new Map<string, Set<string>>();
798
+ // A run in the open workspace moves into review or done with a localhost address in its ## Preview:
799
+ // the Browser opens on it, once per run. The first tick of a workspace only records.
800
+ const mineNow = () => store.S.cards.filter((c) => c.state === ctx!.dir && wsOfCard(c) === ctx!.ws);
801
+ async function autoBrowse() {
802
+ if (!ctx) return;
803
+ const k = ctx.k,
804
+ mine = mineNow(),
805
+ prev = was.get(k);
806
+ was.set(k, new Set(mine.filter(reviewing).map(key)));
807
+ if (!prev) return;
808
+ for (const c of toOpen(mine, prev, saved().seen ?? [], key)) {
809
+ let u: string | undefined;
810
+ try {
811
+ const doc = await (await fetch(`/run/${encodeURIComponent(c.id)}?dir=${encodeURIComponent(c.state)}`)).json();
812
+ u = loopbackUrl(preview(doc.impl));
813
+ } catch {}
814
+ if (!u || ctx?.k !== k || saved().seen?.includes(key(c))) continue;
815
+ (saved().seen ||= []).push(key(c));
816
+ try {
817
+ localStorage.setItem("kz-browse:" + k, u);
818
+ } catch {}
819
+ addTab({ id: "local", kind: "local", title: "Browser" });
820
+ (panes.get("local")?.el as any)?.browseTo?.(u);
821
+ }
822
+ }
823
+
674
824
  export function initRunView() {
675
825
  // A phone's sheet closes with the panel's ×, which here hides the sheet rather than closing the card.
676
826
  document.addEventListener(
@@ -679,9 +829,34 @@ export function initRunView() {
679
829
  if (!document.body.classList.contains("runv") || !(e.target as Element).closest?.("#pclose")) return;
680
830
  e.stopPropagation();
681
831
  document.body.classList.remove("rflip");
832
+ setOpen(false);
682
833
  },
683
834
  true,
684
835
  );
836
+ initPick(pickRun);
837
+ // The sidebar's agent mark: open that workspace with the agent's terminal tab selected.
838
+ addEventListener("kz-open-term", (e: any) => {
839
+ e.preventDefault();
840
+ const { dir, ws, key } = e.detail;
841
+ wantTerm = key;
842
+ if (ctx?.k === wsKey(dir, ws) && document.body.classList.contains("runv")) return void showTerm();
843
+ history.pushState(null, "", wsHref(dir, ws));
844
+ markCurrent();
845
+ go("ws");
846
+ });
847
+ // Search's Tabs group: open the workspace on the screen holding that tab.
848
+ addEventListener("kz-open-tab", (e: any) => {
849
+ e.preventDefault();
850
+ const { dir, ws, id } = e.detail;
851
+ const k = wsKey(dir, ws),
852
+ s = ALL[k],
853
+ sc = s?.screens?.find((x) => leaves(x.tree).includes(id));
854
+ if (sc) (s.on = sc.id), save();
855
+ if (ctx?.k === k && document.body.classList.contains("runv")) return void draw();
856
+ history.pushState(null, "", wsHref(dir, ws));
857
+ markCurrent();
858
+ go("ws");
859
+ });
685
860
  addEventListener("kz-run-preview", openPreview);
686
861
  $("pnotes").onclick = () => void projectNotes();
687
862
  $("pnlist").onclick = (e) => {
@@ -690,7 +865,8 @@ export function initRunView() {
690
865
  };
691
866
  // A /state change: new or ended sessions, the card's own state. Panes stay mounted.
692
867
  addEventListener("kz-state", () => {
693
- if (card && document.body.classList.contains("runv")) void showRunView();
868
+ void autoBrowse();
869
+ if (ctx && document.body.classList.contains("runv")) void showRunView();
694
870
  });
695
871
  }
696
872
  // Opens a card's workspace, its address in the history.