kaizen-agent 1.60.1 → 1.60.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/web/board/git.ts CHANGED
@@ -1,19 +1,19 @@
1
1
  import { store } from "./store.ts";
2
2
  import { post } from "./api.ts";
3
3
  import { key } from "./cards.ts";
4
- import { $, html, raw } from "./dom.ts";
4
+ import { $, html, raw, modal } from "./dom.ts";
5
5
  import { commitMsg } from "./markdown.ts";
6
6
  import { openRun } from "./panel.ts";
7
7
  import { toast } from "./toast.ts";
8
8
 
9
- // The run's Git tab, laid out like Orca's Source Control panel: the branch and its pull
10
- // request at the top, the run's changed files and the message, then one split button
11
- // whose label is the next step (commit, push, open the PR, merge it, remove the worktree)
12
- // with the other steps in its menu, each unavailable one saying why. A run built in the
9
+ // The run's Source control tab, laid out like Orca's: the branch and its pull request at
10
+ // the top, the commit message, one split button (Stage all, then Commit) with every other
11
+ // step in its menu, each unavailable one saying why, the run's staged and unstaged files
12
+ // with their line counts, and the branch's commits at the foot. A run built in the
13
13
  // project's own checkout (no worktree) only commits and pushes.
14
14
 
15
15
  // What the user typed and which inline confirm is open, per run: a refresh redraws the tab.
16
- const ui = new Map<string, { msg?: string; title?: string; body?: string; draft?: boolean; ask?: string }>();
16
+ const ui = new Map<string, { msg?: string; title?: string; body?: string; draft?: boolean; ask?: string; shut?: Record<string, boolean> }>();
17
17
  const st = (c) => {
18
18
  let u = ui.get(key(c));
19
19
  if (!u) ui.set(key(c), (u = {}));
@@ -50,9 +50,11 @@ function steps(c) {
50
50
  b = store.runDoc.branch,
51
51
  pr = b && b.pr,
52
52
  files = g.files.length,
53
+ staged = (g.staged || []).length,
53
54
  open = pr && pr.state === "OPEN";
54
55
  const s = [
55
- { a: "commit", label: "Commit & push", why: files ? "" : "No changes to commit" },
56
+ { a: "commit", label: "Commit", why: staged ? "" : files ? "Stage changes first" : "No changes to commit" },
57
+ { a: "commitpush", label: "Commit & push", why: files ? "" : "No changes to commit" },
56
58
  {
57
59
  a: "push",
58
60
  label: "Push",
@@ -103,6 +105,18 @@ function steps(c) {
103
105
 
104
106
  const PR_WORD = { OPEN: "Open", MERGED: "Merged", CLOSED: "Closed" };
105
107
 
108
+ // Small inline icons Orca's panel uses that the board's sprite does not have.
109
+ const ICO = {
110
+ undo: '<svg viewBox="0 0 24 24"><path d="M9 14 4 9l5-5"/><path d="M4 9h11a5 5 0 0 1 0 10h-4"/></svg>',
111
+ minus: '<svg viewBox="0 0 24 24"><path d="M5 12h14"/></svg>',
112
+ plus: '<svg viewBox="0 0 24 24"><path d="M12 5v14M5 12h14"/></svg>',
113
+ check: '<svg viewBox="0 0 24 24"><path d="m5 12 5 5 9-10"/></svg>',
114
+ file: '<svg viewBox="0 0 24 24"><path d="M14 3H7a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h10a2 2 0 0 0 2-2V8z"/><path d="M14 3v5h5"/></svg>',
115
+ chev: '<svg viewBox="0 0 24 24"><path d="m9 6 6 6-6 6"/></svg>',
116
+ };
117
+ const sum = (rows) => rows.reduce((t, r) => [t[0] + r.add, t[1] + r.del], [0, 0]);
118
+ const counts = ([a, d]) => (a || d ? html`<span class="gnum"><i class="ad">+${a}</i><i class="de">-${d}</i></span>` : "");
119
+
106
120
  export function gitTab(c, refresh) {
107
121
  const body = $("pbody");
108
122
  // A refresh while the user types or a step runs would lose the text or the busy label.
@@ -117,134 +131,153 @@ export function gitTab(c, refresh) {
117
131
  pr = b && b.pr,
118
132
  u = st(c),
119
133
  all = steps(c),
120
- next = all.find((x) => !x.why && x.a !== "draft"),
121
- files = g.files.length,
134
+ rows = g.rows || [],
135
+ staged = rows.filter((r) => r.staged),
136
+ unstaged = rows.filter((r) => !r.staged),
122
137
  target = b ? `origin/${b.base}` : `${g.remote}/${g.branch || "HEAD"}`;
123
138
  if (u.msg === undefined) u.msg = commitMsg(store.runDoc.impl) || c.title || c.text || "";
139
+ u.shut = u.shut || {};
140
+ // The main button: Stage all while nothing is staged, Commit once something is, else the
141
+ // next remote step (push, PR, merge, remove), else a Commit with nothing to do.
142
+ const later = all.find((x) => !x.why && !["commit", "commitpush", "draft"].includes(x.a));
143
+ const main = staged.length
144
+ ? { a: "commit", label: "Commit", ico: ICO.check }
145
+ : unstaged.length
146
+ ? { a: "stageall", label: "Stage all", ico: ICO.plus }
147
+ : later
148
+ ? { a: later.a, label: later.label, ico: "" }
149
+ : { a: "", label: "Commit", ico: ICO.check };
124
150
  const chip = pr
125
- ? html`<a
126
- class="gchip ${pr.state.toLowerCase()}${pr.draft ? " draft" : ""}"
127
- href="${pr.url}"
128
- target="_blank"
129
- rel="noopener"
130
- title="Open on GitHub"
131
- ><svg><use href="#t-git" /></svg>#${pr.number}
132
- ${pr.draft && pr.state === "OPEN" ? "Draft" : PR_WORD[pr.state] || pr.state}</a
151
+ ? html`<a class="gchip ${pr.state.toLowerCase()}${pr.draft ? " draft" : ""}" href="${pr.url}" target="_blank" rel="noopener" title="Open on GitHub"
152
+ ><svg><use href="#t-git" /></svg>#${pr.number} ${pr.draft && pr.state === "OPEN" ? "Draft" : PR_WORD[pr.state] || pr.state}</a
133
153
  >`
134
154
  : b && b.checking
135
155
  ? html`<span class="gchip dim">Checking PR…</span>`
136
156
  : b && b.gh && !all.find((x) => x.a === "pr").why
137
- ? html`<button class="gchip" data-a="pr">
138
- <svg><use href="#t-git" /></svg>Create PR
139
- </button>`
157
+ ? html`<button class="gchip" data-a="pr"><svg><use href="#t-git" /></svg>Create PR</button>`
140
158
  : "";
141
- const k = store.runDoc.commit;
142
- const empty = files
143
- ? ""
144
- : html`<div class="gempty">
145
- <b
146
- >${pr && pr.state === "MERGED" ? "Merged" : b && b.landed ? "On " + b.base : g.ahead > 0 && (!b || b.upstream) ? "Not pushed yet" : "No changes to commit"}</b
147
- ><span
148
- >${
149
- pr && pr.state === "MERGED"
150
- ? `Pull request #${pr.number} is merged into ${b.base}. The worktree and its branch can go.`
151
- : b && b.landed
152
- ? `Every commit of ${b.branch} is on ${b.base}. The worktree can go.`
153
- : g.ahead > 0 && (!b || b.upstream)
154
- ? `${g.ahead} commit${g.ahead === 1 ? "" : "s"} ahead of ${target}.`
155
- : pr && pr.state === "OPEN"
156
- ? `Pull request #${pr.number} is open against ${b.base}.`
157
- : b && !b.upstream
158
- ? `${b.branch} is not on GitHub yet. Create PR pushes it and opens the pull request.`
159
- : `Up to date with ${target}.`
160
- }</span
161
- >${k && k.sha ? html`<span class="dim">Last commit <code>${k.sha}</code>${k.pushed ? " pushed" : " not pushed"}.</span>` : ""}
162
- </div>`;
163
- const changes = files
164
- ? html`<div class="gsec">
165
- <div class="ghd">Changes <span class="n">${files}</span></div>
166
- <pre class="files">${g.files.join("\n")}</pre>
167
- ${g.others ? html`<div class="dim">${g.others} other changed file${g.others === 1 ? " is" : "s are"} left alone: they are not this run's.</div>` : ""}${
168
- g.shared && g.shared.length
169
- ? html`<div class="dim">These files also hold other runs' changes, and a file is committed whole:</div>
170
- <pre class="files">${g.shared.join("\n")}</pre>`
171
- : ""
172
- }<textarea id="gmsg" aria-label="Commit message" placeholder="feat(area): what changed">${u.msg}</textarea>
173
- <div class="dim" id="glong" hidden>The first line is over 72 characters; logs will cut it short.</div>
159
+ const row = (r) => {
160
+ const i = r.path.lastIndexOf("/"),
161
+ name = r.path.slice(i + 1),
162
+ dir = i > 0 ? r.path.slice(0, i) : "";
163
+ return html`<li class="grow" title="${r.path}">
164
+ <span class="gico">${raw(ICO.file)}</span><span class="gname">${name}${dir ? html`<small>${dir}</small>` : ""}</span>
165
+ <span class="gside">
166
+ <span class="gacts">${raw(
167
+ r.staged
168
+ ? html`<button class="ib" data-a="unstage" data-p="${r.path}" title="Unstage" aria-label="Unstage ${r.path}">${raw(ICO.minus)}</button>`
169
+ : html`<button class="ib" data-a="discard" data-p="${r.path}" data-u="${r.code === "U" ? 1 : ""}" title="Discard changes" aria-label="Discard changes to ${r.path}">${raw(ICO.undo)}</button><button class="ib" data-a="stage" data-p="${r.path}" title="Stage" aria-label="Stage ${r.path}">${raw(ICO.plus)}</button>`,
170
+ )}</span>
171
+ <span class="gmeta">${counts([r.add, r.del])}<span class="gcode c-${r.code}">${r.code}</span></span>
172
+ </span>
173
+ </li>`;
174
+ };
175
+ const group = (k, title, list) =>
176
+ list.length
177
+ ? html`<section class="ggrp${u.shut[k] ? " shut" : ""}">
178
+ <div class="ghd">
179
+ <button class="gtog" data-a="tog" data-k="${k}" aria-expanded="${!u.shut[k]}">${raw(ICO.chev)}${title} <span class="n">${list.length}</span></button>
180
+ <span class="gacts on">${raw(
181
+ k === "staged"
182
+ ? html`<button class="ib" data-a="unstageall" title="Unstage all" aria-label="Unstage all">${raw(ICO.minus)}</button>`
183
+ : html`<button class="ib" data-a="discardall" title="Discard all changes" aria-label="Discard all changes">${raw(ICO.undo)}</button><button class="ib" data-a="stageall" title="Stage all" aria-label="Stage all">${raw(ICO.plus)}</button>`,
184
+ )}</span>
185
+ </div>
186
+ <ul class="glist">${raw(list.map(row).join(""))}</ul>
187
+ </section>`
188
+ : "";
189
+ const noChange = !rows.length
190
+ ? html`<div class="gempty">
191
+ <b>${pr && pr.state === "MERGED" ? "Merged" : b && b.landed ? "On " + b.base : g.ahead > 0 && (!b || b.upstream) ? "Not pushed yet" : "No changes on this branch"}</b>
192
+ <span>${
193
+ pr && pr.state === "MERGED"
194
+ ? `Pull request #${pr.number} is merged into ${b.base}. The worktree and its branch can go.`
195
+ : b && b.landed
196
+ ? `Every commit of ${b.branch} is on ${b.base}. The worktree can go.`
197
+ : g.ahead > 0 && (!b || b.upstream)
198
+ ? `${g.ahead} commit${g.ahead === 1 ? "" : "s"} ahead of ${target}.`
199
+ : b && !b.upstream
200
+ ? `${b.branch} is not on GitHub yet. Create PR pushes it.`
201
+ : `This workspace is clean and has no changes ahead of ${target}.`
202
+ }</span>
174
203
  </div>`
175
204
  : "";
205
+ // What Orca has no room for: files that are other runs', said on hover of the totals.
206
+ const aside = [g.others ? `${g.others} other changed file${g.others === 1 ? " is" : "s are"} not this run's` : "", ...(g.shared && g.shared.length ? [`Also holds other runs' changes: ${g.shared.map((x) => x.split(":")[0]).join(", ")}`] : [])].filter(Boolean).join("\n");
176
207
  // The inline confirm or form the last click opened, in place of the split button.
177
208
  const ask =
178
209
  u.ask === "pr" || u.ask === "draft"
179
210
  ? html`<div class="gsec gform">
180
211
  <div class="ghd">${u.ask === "draft" ? "Draft pull request" : "Pull request"} into ${b.base}</div>
181
- <input
182
- id="gtitle"
183
- aria-label="Title"
184
- value="${u.title ?? (commitMsg(store.runDoc.impl) || c.title || "").split("\n")[0]}"
185
- /><textarea id="gbody" aria-label="Description">${u.body ?? `Run ${c.id}.`}</textarea>
212
+ <input id="gtitle" aria-label="Title" value="${u.title ?? (commitMsg(store.runDoc.impl) || c.title || "").split("\n")[0]}" /><textarea id="gbody" aria-label="Description">${u.body ?? `Run ${c.id}.`}</textarea>
186
213
  <div class="row">
187
214
  <button class="btn ghost" data-a="cancel">Cancel</button
188
- ><button class="btn pri" data-a="go-${u.ask}">
189
- ${b.upstream && g.ahead === 0 ? "" : "Push & "}${u.ask === "draft" ? "create draft PR" : "create PR"}
190
- </button>
215
+ ><button class="btn pri" data-a="go-${u.ask}">${b.upstream && g.ahead === 0 ? "" : "Push & "}${u.ask === "draft" ? "create draft PR" : "create PR"}</button>
191
216
  </div>
192
217
  </div>`
193
218
  : u.ask === "merge"
194
219
  ? html`<div class="gsec gform">
195
220
  <div class="ghd">Merge #${pr.number} into ${b.base} by rebase?</div>
196
- <div class="dim">The worktree stays until you remove it.</div>
197
- <div class="row">
198
- <button class="btn ghost" data-a="cancel">Cancel</button
199
- ><button class="btn pri" data-a="go-merge">Merge PR</button>
200
- </div>
221
+ <div class="row"><button class="btn ghost" data-a="cancel">Cancel</button><button class="btn pri" data-a="go-merge">Merge PR</button></div>
201
222
  </div>`
202
223
  : u.ask === "remove"
203
224
  ? html`<div class="gsec gform">
204
225
  <div class="ghd">Remove the worktree and delete ${b.branch}?</div>
205
226
  <div class="dim">Its work is on ${b.base}. The branch is deleted here and on GitHub.</div>
206
- <div class="row">
207
- <button class="btn ghost" data-a="cancel">Cancel</button
208
- ><button class="btn danger" data-a="go-remove">Remove workspace</button>
209
- </div>
227
+ <div class="row"><button class="btn ghost" data-a="cancel">Cancel</button><button class="btn danger" data-a="go-remove">Remove workspace</button></div>
210
228
  </div>`
211
229
  : "";
212
230
  const menu = all
213
- .map(
214
- (x) =>
215
- html`<button data-a="${x.a}" ${x.why ? " disabled" : ""}>
216
- <span>${x.label}</span>${x.why ? html`<small>${x.why}</small>` : ""}
217
- </button>`,
218
- )
219
- .concat(
220
- pr
221
- ? [
222
- html`<hr />
223
- <a href="${pr.url}" target="_blank" rel="noopener">Open PR on GitHub</a>`,
224
- ]
225
- : [],
226
- );
231
+ .map((x) => html`<button data-a="${x.a}" ${x.why ? " disabled" : ""}><span>${x.label}</span>${x.why ? html`<small>${x.why}</small>` : ""}</button>`)
232
+ .concat(pr ? [html`<hr /><a href="${pr.url}" target="_blank" rel="noopener">Open PR on GitHub</a>`] : []);
227
233
  const split = ask
228
234
  ? ""
229
235
  : html`<div class="split gsplit">
230
- <button class="btn ${next ? "pri" : ""}" data-a="${next ? next.a : ""}" ${next ? "" : " disabled"}>
231
- ${next ? next.label : "Up to date"}</button
232
- ><button class="btn ${next ? "pri" : ""} gmore" aria-label="More git actions" aria-haspopup="menu">
233
- <svg><use href="#i-chev" /></svg>
234
- </button>
236
+ <button class="btn" data-a="${main.a}" ${main.a ? "" : " disabled"}>${raw(main.ico)}${main.label}</button
237
+ ><button class="btn gmore" aria-label="More commit and remote actions" title="More commit and remote actions" aria-haspopup="menu"><svg><use href="#i-chev" /></svg></button>
235
238
  <div class="menu-pop" role="menu" hidden>${raw(menu.join(""))}</div>
236
239
  </div>`;
240
+ const log = g.log || [];
241
+ const commits = log.length
242
+ ? html`<section class="glog${u.shut.log ? " shut" : ""}">
243
+ <div class="ghd"><button class="gtog" data-a="tog" data-k="log" aria-expanded="${!u.shut.log}">${raw(ICO.chev)}Commits <span class="n">${log.length}${log.length >= 50 ? "+" : ""}</span></button></div>
244
+ <ol class="gcommits">${raw(
245
+ log
246
+ .map((l, i) => {
247
+ const head = i === 0 && (b ? b.branch : g.branch);
248
+ return html`<li class="${i === 0 ? "head" : ""}${l.unpushed ? " up" : ""}" title="${l.sha}${l.unpushed ? " (not pushed)" : ""}"><i></i><span>${l.subject}</span>${head ? html`<em>${head}</em>` : ""}</li>`;
249
+ })
250
+ .join(""),
251
+ )}</ol>
252
+ </section>`
253
+ : "";
237
254
  body.innerHTML = html`<div class="gitp">
238
255
  <div class="ghead">
239
256
  ${chip}
240
- <div class="gbr" title="${g.branch}">${b ? b.branch : g.branch || "HEAD"}</div>
241
- <div class="gto">→ ${target}</div>
257
+ <div class="gbr" title="${aside || g.branch}"><span>${b ? b.branch : g.branch || "HEAD"}</span>${counts(sum(rows))}</div>
258
+ <div class="gto">→ ${target}${pr ? html`<a class="ib" href="${pr.url}" target="_blank" rel="noopener" title="Open on GitHub" aria-label="Open on GitHub"><svg><use href="#i-ext" /></svg></a>` : ""}</div>
242
259
  </div>
243
- ${changes}${empty}${ask}${split}
260
+ ${rows.length ? html`<div class="gmsgbox"><textarea id="gmsg" aria-label="Commit message" placeholder="Message">${u.msg}</textarea><button class="ib gspark" data-a="spark" title="Write a commit message from the changes" aria-label="Write a commit message from the changes"><svg><use href="#i-ai" /></svg></button></div><div class="dim" id="glong" hidden>First line over 72 characters.</div>` : ""}
261
+ ${noChange}${ask}${split}
262
+ ${group("staged", "Staged changes", staged)}${group("changes", "Changes", unstaged)}
263
+ ${commits}
244
264
  </div>`;
245
265
  wire(c, body.querySelector(".gitp"));
246
266
  }
247
267
 
268
+ // Orca's confirm: the file named, Cancel or a red Discard. Resolves true on Discard.
269
+ function confirmDiscard(path, untracked, many = 0) {
270
+ return new Promise((res) => {
271
+ const dl = modal(html`<div class="gdis">
272
+ <b>${many ? `Discard all ${many} unstaged changes?` : html`Discard changes to "${path.split("/").pop()}"?`}</b>
273
+ <p>${many ? "This reverts every unstaged file below; new files are deleted." : untracked ? "This will delete this new file." : "This will revert the unstaged changes to this file."} This cannot be undone.</p>
274
+ <div class="gpath">${path}</div>
275
+ <div class="row"><button class="btn" value="no">Cancel</button><button class="btn danger" value="yes">${raw(ICO.undo)}Discard</button></div>
276
+ </div>`);
277
+ dl.addEventListener("close", () => res(dl.returnValue === "yes"));
278
+ });
279
+ }
280
+
248
281
  function wire(c, el) {
249
282
  const u = st(c),
250
283
  inp = el.querySelector("#gmsg");
@@ -277,7 +310,8 @@ function wire(c, el) {
277
310
  }
278
311
 
279
312
  const BUSY = {
280
- commit: "Pushing…",
313
+ commit: "Committing…",
314
+ commitpush: "Pushing…",
281
315
  push: "Pushing…",
282
316
  "go-pr": "Creating PR…",
283
317
  "go-draft": "Creating PR…",
@@ -290,14 +324,52 @@ async function act(c, a, b) {
290
324
  if (a === "cancel") return ((u.ask = undefined), gitTab(c, false));
291
325
  // Steps that need a second look open their form or confirm first.
292
326
  if (a === "pr" || a === "draft" || a === "merge" || a === "remove") return ((u.ask = a), gitTab(c, false));
293
- if (a === "commit" && !(u.msg || "").trim()) return toast("A commit message is required");
327
+ if (a === "tog") {
328
+ u.shut = { ...u.shut, [b.dataset.k]: !u.shut?.[b.dataset.k] };
329
+ return gitTab(c, false);
330
+ }
331
+ const g = store.runDoc.git;
332
+ if (a === "spark") {
333
+ b.disabled = true;
334
+ b.dataset.busy = 1;
335
+ b.classList.add("spin");
336
+ const r = await post("/commit-message", { dir: c.state, id: c.id });
337
+ b.classList.remove("spin");
338
+ delete b.dataset.busy;
339
+ if (r.ok) {
340
+ u.msg = r.message;
341
+ if (!r.ai) toast("Claude was not available: wrote a plain message");
342
+ }
343
+ if (store.openKey === key(c)) gitTab(c, false);
344
+ return;
345
+ }
346
+ if (a === "stage" || a === "unstage" || a === "stageall" || a === "unstageall" || a === "discard" || a === "discardall") {
347
+ const open = (g.rows || []).filter((r) => !r.staged);
348
+ const paths =
349
+ a === "stageall" || a === "discardall"
350
+ ? open.map((r) => r.path)
351
+ : a === "unstageall"
352
+ ? g.staged || []
353
+ : [b.dataset.p];
354
+ if (a === "discard" && !(await confirmDiscard(b.dataset.p, !!b.dataset.u))) return;
355
+ if (a === "discardall" && !(await confirmDiscard(paths.join("\n"), false, paths.length))) return;
356
+ b.disabled = true;
357
+ b.dataset.busy = 1;
358
+ const r = await post("/stage", { dir: c.state, id: c.id, op: a === "discardall" ? "discard" : a.replace("all", ""), paths });
359
+ delete b.dataset.busy;
360
+ if (store.openKey === key(c)) await openRun(c, false, true);
361
+ return;
362
+ }
363
+ if ((a === "commit" || a === "commitpush") && !(u.msg || "").trim()) return toast("A commit message is required");
294
364
  b.disabled = true;
295
365
  b.dataset.busy = 1;
296
366
  b.textContent = BUSY[a] || "Working…";
297
367
  const base = { dir: c.state, id: c.id };
298
368
  const r =
299
- a === "commit" || a === "push"
300
- ? await post("/commit", { ...base, message: a === "commit" ? u.msg : "", files: store.runDoc.git.files })
369
+ a === "commit"
370
+ ? await post("/commit", { ...base, message: u.msg, files: g.staged || [], push: false })
371
+ : a === "commitpush" || a === "push"
372
+ ? await post("/commit", { ...base, message: a === "commitpush" ? u.msg : "", files: g.files })
301
373
  : a === "go-pr" || a === "go-draft"
302
374
  ? await post("/pr", {
303
375
  ...base,
@@ -309,7 +381,9 @@ async function act(c, a, b) {
309
381
  : await post("/pr", { ...base, op: a === "go-merge" ? "merge" : "remove" });
310
382
  if (r.ok) {
311
383
  toast(
312
- a === "commit" || a === "push"
384
+ a === "commit"
385
+ ? "Committed " + r.sha
386
+ : a === "commitpush" || a === "push"
313
387
  ? "Committed & pushed " + r.sha
314
388
  : a === "go-merge"
315
389
  ? "Merged"
package/web/board/live.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import { store } from "./store.ts";
2
- import { load } from "./api.ts";
2
+ import { flushLoad, load } from "./api.ts";
3
3
  import { $ } from "./dom.ts";
4
4
  import { iceBusy, openSources, srcOpen } from "./icebox.ts";
5
5
  import { deep } from "./panel.ts";
@@ -39,6 +39,7 @@ export function initLive() {
39
39
  addEventListener("kz-view", () => { if (pendingReload && !document.body.classList.contains("homev")) location.reload(); });
40
40
  // Back from a terminal: what was committed or pushed there touched nothing the server watches.
41
41
  addEventListener("focus", () => load(true));
42
+ addEventListener("visibilitychange", flushLoad);
42
43
  // No view in the address is Home.
43
44
  const first = ["settings", "sources", "terminal", "board", "ideas", "run"].includes(v0) ? v0 : "home";
44
45
  markView(first);
package/web/board/main.ts CHANGED
@@ -17,6 +17,7 @@ import { initContext } from "./context.ts";
17
17
  import { cardHref, initFooter, initRail, markCurrent, wsHref } from "./workspace.ts";
18
18
  import { go } from "./views.ts";
19
19
  import { openWorkspace } from "./run-view.ts";
20
+ import { initOnboarding } from "./onboarding.ts";
20
21
 
21
22
  initPanel();
22
23
  initViews();
@@ -88,3 +89,4 @@ document.addEventListener(
88
89
  },
89
90
  true,
90
91
  );
92
+ void initOnboarding();
@@ -0,0 +1,223 @@
1
+ // First-run onboarding: one panel over the board with three steps (default agent, look,
2
+ // notifications), then "Add your first project". Where a user got to is kept by the board in
3
+ // ~/.kaizen/onboarding.json (/onboarding), so a skipped or half-done flow can be continued from the
4
+ // side menu's Setup row or the "Continue setup?" popup. Existing users, who have a project, never see it.
5
+ import { html, raw } from "./dom.ts";
6
+ import { openAdd } from "./add-project.ts";
7
+
8
+ type Cfg = { show: boolean; resume: boolean; step: number; total: number; default: string; installed: string[]; agents: { cmd: string; name: string }[]; install: Record<string, { command?: string; docs: string }> };
9
+ // The tools agent.default accepts.
10
+ const PICKABLE = ["claude", "codex", "agy", "opencode", "gemini"];
11
+ const MOD = /Mac|iP(hone|ad)/.test(navigator.platform) ? "⌘" : "Ctrl";
12
+ const NAMES = ["Default agent", "Appearance", "Notifications"];
13
+ const ASKED = "kz-onb-asked";
14
+
15
+ async function call(path: string, body?: object) {
16
+ try {
17
+ const r = await fetch(path, body ? { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) } : undefined);
18
+ return r.ok ? await r.json() : null;
19
+ } catch {
20
+ return null;
21
+ }
22
+ }
23
+
24
+ let cfg: Cfg | null = null;
25
+ let dlg: HTMLDialogElement | null = null;
26
+ let step = 0;
27
+ let agent = "";
28
+ let theme = "system";
29
+ let more = false;
30
+
31
+ // The side menu's Setup row follows what is saved.
32
+ const row = (s: number, outcome: string | null) =>
33
+ (window as any).kzSetupRow?.({ resume: outcome === "skipped" || (outcome === null && s > 0), step: s, total: cfg?.total ?? 3 });
34
+
35
+ const save = (patch: { step?: number; outcome?: string | null }) => {
36
+ row(patch.step ?? step, patch.outcome ?? null);
37
+ return call("/onboarding", patch);
38
+ };
39
+
40
+ function storedTheme() {
41
+ try {
42
+ const t = localStorage.getItem("kz-theme");
43
+ return t === "light" || t === "dark" ? t : "system";
44
+ } catch {
45
+ return "system";
46
+ }
47
+ }
48
+ const notif = () => (!("Notification" in window) || !window.isSecureContext ? "na" : Notification.permission);
49
+
50
+ const preview = (k: string) => html`<span class="pv ${k}"><i class="sb"></i><i class="ln"></i><i class="ln s"></i></span>`;
51
+
52
+ function agents() {
53
+ const c = cfg!;
54
+ const all = c.agents.filter((a) => PICKABLE.includes(a.cmd));
55
+ const det = all.filter((a) => c.installed.includes(a.cmd)),
56
+ rest = all.filter((a) => !c.installed.includes(a.cmd));
57
+ const card = (a: { cmd: string; name: string }, off: boolean) =>
58
+ html`<button type="button" class="onb-card" role="radio" aria-checked="${String(agent === a.cmd)}" data-agent="${a.cmd}"><svg><use href="#c-${a.cmd}"/></svg><span>${a.name}${off ? html`<small>Not found</small>` : ""}</span><i class="ck"></i></button>`;
59
+ // The picked agent is not on PATH: how to install it, and that carrying on is fine.
60
+ const sel = all.find((a) => a.cmd === agent && !c.installed.includes(a.cmd));
61
+ const how = sel ? c.install?.[sel.cmd] : null;
62
+ const help = sel
63
+ ? html`<div class="onb-panel"><p><b>${sel.name}</b> is not installed yet.${how?.command ? " Run this in a terminal, then open kaizen again." : ""} You can carry on now: kaizen uses it as soon as it is on your PATH.</p>${how?.command ? html`<div class="onb-cmd"><code>${how.command}</code><button type="button" class="btn" data-a="copy" data-cmd="${how.command}">Copy</button></div>` : ""}${how ? html`<a class="onb-lnk" href="${how.docs}" target="_blank" rel="noopener">Install instructions</a>` : ""}</div>`
64
+ : "";
65
+ if (!det.length)
66
+ return html`<p class="onb-note">No agents found on your PATH. Pick the one you will use to see how to install it, or carry on.</p><div class="onb-grid" role="radiogroup" aria-label="Default agent">${all.map((a) => card(a, true))}</div>${help}`;
67
+ return html`<div class="onb-lbl">Detected on your system <span>${det.length}</span></div><div class="onb-grid" role="radiogroup" aria-label="Default agent">${det.map((a) => card(a, false))}${more ? rest.map((a) => card(a, true)) : ""}</div>${rest.length ? html`<button type="button" class="onb-lnk" data-a="more">${more ? "Hide agents" : `Show ${rest.length} more ${rest.length === 1 ? "agent" : "agents"} →`}</button>` : ""}${help}`;
68
+ }
69
+
70
+ function looks() {
71
+ const t = (k: string, name: string, hint: string, ic: string) =>
72
+ html`<button type="button" class="onb-card th" role="radio" aria-checked="${String(theme === k)}" data-theme="${k}">${preview(k)}<span class="cap"><b>${raw(ic)}${name}</b><small>${hint}</small></span><i class="ck"></i></button>`;
73
+ const I = (d: string) => `<svg viewBox="0 0 24 24"><path d="${d}"/></svg>`;
74
+ return html`<div class="onb-themes" role="radiogroup" aria-label="Theme">${t("system", "System", "Match OS", I("M3 5h18v11H3zM8 20h8M12 16v4"))}${t("dark", "Dark", "Easy on the eyes", I("M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z"))}${t("light", "Light", "Bright & crisp", I("M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 2v2M12 20v2M4 12H2M22 12h-2M5 5l1.5 1.5M17.5 17.5 19 19M5 19l1.5-1.5M17.5 6.5 19 5"))}</div><p class="onb-note"><svg viewBox="0 0 24 24"><path d="M4 7h10M18 7h2M4 17h2M10 17h10M14 5v4M8 15v4"/></svg><span>Motion, density and more live in <b>Settings</b>.</span></p>`;
75
+ }
76
+
77
+ function alerts() {
78
+ const s = notif();
79
+ const msg = {
80
+ na: "Notifications are not available at this address. Open the board at localhost or over HTTPS to turn them on.",
81
+ default: "Allow notifications so a run that needs you, or an agent that finishes, reaches you in another window.",
82
+ granted: "Notifications are on. kaizen will tell you when a run needs you or an agent is done.",
83
+ denied: "Notifications are blocked for this site. Allow them in your browser's site settings, then come back.",
84
+ }[s];
85
+ return html`<div class="onb-panel"><p>${msg}</p><div class="onb-row">${s === "default" ? html`<button type="button" class="btn pri" data-a="allow">Allow notifications</button>` : ""}${s === "granted" ? html`<button type="button" class="btn" data-a="test">Send test notification</button>` : ""}</div></div>`;
86
+ }
87
+
88
+ const COPY = [
89
+ { 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 },
90
+ { title: "Choose your look", sub: "Follow your system, or pick light or dark. You can change it any time.", body: looks },
91
+ { title: "Set up notifications", sub: "kaizen can tell you when a run needs you or an agent is done.", body: alerts },
92
+ ];
93
+
94
+ function draw() {
95
+ const c = cfg!,
96
+ last = step === c.total - 1,
97
+ s = COPY[step];
98
+ dlg!.innerHTML = String(html`
99
+ <div class="onb-hd"><pre class="mark"><span>█ █ ▄▀█ █ ▀▀█ █▀▀ █▄ █</span>
100
+ <span>█▀▄ █▀█ █ ▄▀ ██▄ █ ▀█</span>
101
+ <span>█ █ █ █ █ █▄▄ █▄▄ █ █</span></pre></div>
102
+ <div class="onb-prog">${COPY.map((_, i) => html`<button type="button" class="${i === step ? "on" : i < step ? "was" : ""}" data-s="${i}" aria-label="Go to step ${i + 1}: ${NAMES[i]}" title="${NAMES[i]}"></button>`)}<span>${step + 1} of ${c.total}</span></div>
103
+ <div class="onb-main">${step === 0 ? html`<small class="onb-eb">Welcome to kaizen</small>` : ""}<h2>${s.title}</h2><p class="onb-sub">${s.sub}</p>${s.body()}</div>
104
+ <div class="onb-ft"><button type="button" class="onb-lnk" data-a="skip">Skip to project setup</button><span></span>${step > 0 ? html`<button type="button" class="btn" data-a="back">‹ Back</button>` : ""}<button type="button" class="btn pri" data-a="next">${last ? "Add your first project" : "Continue"}<kbd>${MOD} ↵</kbd></button></div>`);
105
+ dlg!.querySelector<HTMLElement>(step === 0 ? ".onb-card[aria-checked=true]" : "[data-a=next]")?.focus();
106
+ }
107
+
108
+ function close() {
109
+ dlg?.close();
110
+ dlg?.remove();
111
+ dlg = null;
112
+ }
113
+
114
+ // The agent picked on the first step is saved when the user leaves it, by Continue or by a progress bar.
115
+ const keepAgent = () => (step === 0 && agent ? call("/settings", { key: "agent.default", value: agent }) : null);
116
+
117
+ async function next() {
118
+ const c = cfg!;
119
+ await keepAgent();
120
+ if (step < c.total - 1) {
121
+ step++;
122
+ void save({ step });
123
+ return draw();
124
+ }
125
+ void save({ outcome: "done" });
126
+ close();
127
+ openAdd({ start: "folder" });
128
+ }
129
+
130
+ function ask(title: string, text: string, btns: [string, string, boolean?][]) {
131
+ return new Promise<string>((res) => {
132
+ const d = document.createElement("dialog");
133
+ d.className = "onb-ask";
134
+ d.innerHTML = String(html`<h3>${title}</h3><p>${text}</p><div class="onb-row">${btns.map(([k, l, pri]) => html`<button type="button" class="btn${pri ? " pri" : ""}" data-k="${k}">${l}</button>`)}</div>`);
135
+ d.oncancel = (e) => (e.preventDefault(), d.close(), d.remove(), res(btns[btns.length - 1][0]));
136
+ d.onclick = (e) => {
137
+ const k = (e.target as HTMLElement).closest<HTMLElement>("[data-k]")?.dataset.k;
138
+ if (k) (d.close(), d.remove(), res(k));
139
+ };
140
+ document.body.appendChild(d);
141
+ d.showModal();
142
+ d.querySelector<HTMLElement>(".pri")?.focus();
143
+ });
144
+ }
145
+
146
+ async function skip() {
147
+ if ((await ask("Skip onboarding?", "It won't take long!", [["skip", "Skip"], ["keep", "No, keep going", true]])) !== "skip") return;
148
+ void save({ outcome: "skipped" });
149
+ close();
150
+ openAdd({ start: "folder" });
151
+ }
152
+
153
+ function open(at: number) {
154
+ if (dlg || !cfg) return;
155
+ step = Math.max(0, Math.min(cfg.total - 1, at));
156
+ agent = PICKABLE.includes(cfg.default) ? cfg.default : (cfg.agents.find((a) => PICKABLE.includes(a.cmd) && cfg!.installed.includes(a.cmd))?.cmd ?? "");
157
+ theme = storedTheme();
158
+ more = false;
159
+ dlg = document.createElement("dialog");
160
+ dlg.className = "onb";
161
+ dlg.setAttribute("aria-label", "Welcome to kaizen");
162
+ dlg.oncancel = (e) => (e.preventDefault(), void skip());
163
+ dlg.onclick = (e) => {
164
+ const t = e.target as HTMLElement;
165
+ const b = t.closest<HTMLElement>("button");
166
+ if (!b) return;
167
+ const d = b.dataset;
168
+ if (d.agent) ((agent = d.agent), draw());
169
+ else if (d.theme) {
170
+ theme = d.theme;
171
+ (window as any).setTheme?.(theme);
172
+ draw();
173
+ } else if (d.s) (void keepAgent(), (step = +d.s), void save({ step }), draw());
174
+ else if (d.a === "more") ((more = !more), draw());
175
+ else if (d.a === "back") (step--, void save({ step }), draw());
176
+ else if (d.a === "next") void next();
177
+ else if (d.a === "skip") void skip();
178
+ else if (d.a === "allow") void Notification.requestPermission().then(draw, draw);
179
+ else if (d.a === "copy") {
180
+ void navigator.clipboard?.writeText(d.cmd ?? "").then(() => (b.textContent = "Copied"), () => (b.textContent = "Select and copy"));
181
+ } else if (d.a === "test") new Notification("kaizen", { body: "This is how kaizen will tell you something needs you.", icon: "/logo.png" });
182
+ };
183
+ // Ctrl/Cmd+Enter always continues; a bare Enter does unless a button (other than a choice card) or field holds focus.
184
+ dlg.onkeydown = (e) => {
185
+ if (e.key !== "Enter" || e.isComposing) return;
186
+ const on = (e.target as HTMLElement).closest("button:not(.onb-card),input,select,textarea");
187
+ if (e.ctrlKey || e.metaKey || !on) (e.preventDefault(), void next());
188
+ };
189
+ document.body.appendChild(dlg);
190
+ dlg.showModal();
191
+ draw();
192
+ }
193
+
194
+ // The popup for someone who skipped or left it half done: once per browser session.
195
+ async function offer() {
196
+ try {
197
+ if (sessionStorage.getItem(ASKED)) return;
198
+ sessionStorage.setItem(ASKED, "1");
199
+ } catch {}
200
+ const c = cfg!;
201
+ const r = await ask("Continue setup?", c.step > 0 ? `You are on step ${c.step + 1} of ${c.total}. It only takes a minute.` : "You skipped setup. It only takes a minute.", [
202
+ ["go", "Continue", true],
203
+ ["later", "Not now"],
204
+ ["never", "Don't ask again"],
205
+ ]);
206
+ if (r === "go") open(c.step);
207
+ else if (r === "never") (void save({ outcome: "dismissed" }), row(0, "dismissed"));
208
+ }
209
+
210
+ export async function initOnboarding() {
211
+ cfg = await call("/onboarding");
212
+ if (!cfg) return;
213
+ (window as any).kzSetupRow?.(cfg);
214
+ document.getElementById("rsetup")?.addEventListener("click", (e) => (e.preventDefault(), open(cfg!.step)));
215
+ const q = new URLSearchParams(location.search);
216
+ if (q.has("setup")) {
217
+ q.delete("setup");
218
+ history.replaceState(null, "", location.pathname + (q.toString() ? "?" + q : "") + location.hash);
219
+ return open(cfg.resume ? cfg.step : 0);
220
+ }
221
+ if (cfg.show) return open(0);
222
+ if (cfg.resume) void offer();
223
+ }