kaizen-agent 1.60.0 → 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/api.ts CHANGED
@@ -21,8 +21,31 @@ let before: Map<string, [number, boolean]> | null = null;
21
21
  // tab or a phone picking a project never moves this one.
22
22
  export const dirHeader = () => (store.dir ? { "x-kz-dir": store.dir } : {});
23
23
  let latestLoad = 0;
24
+ // A change event can come several times a second while agents work, and a full read and
25
+ // redraw blocks this thread (and any terminal in it). One quiet load per QUIET_GAP, the
26
+ // last change always covered; a hidden tab only watches for agents asking.
27
+ const QUIET_GAP = 500, HIDDEN_GAP = 5000;
28
+ // The last reply without its clock, and when it was last drawn: an identical reply skips
29
+ // the redraw, but ages and repeat notices still need one now and then.
30
+ const REDRAW_MS = 30_000;
31
+ let lastBody = "", drawnAt = 0;
32
+ let lastQuiet = 0;
33
+ let quietTimer: ReturnType<typeof setTimeout> | 0 = 0;
34
+ const runQuiet = () => {
35
+ quietTimer = 0;
36
+ lastQuiet = Date.now();
37
+ return read(true);
38
+ };
24
39
  // quiet: the server said something changed, nobody asked for a redraw.
25
- export async function load(quiet) {
40
+ export function load(quiet?: boolean) {
41
+ if (!quiet) return read(false);
42
+ if (!quietTimer) quietTimer = setTimeout(runQuiet, Math.max(0, lastQuiet + (document.hidden ? HIDDEN_GAP : QUIET_GAP) - Date.now()));
43
+ }
44
+ // Back on a hidden tab: what it put off is shown now.
45
+ export function flushLoad() {
46
+ if (!document.hidden && quietTimer) { clearTimeout(quietTimer); void runQuiet(); }
47
+ }
48
+ async function read(quiet: boolean) {
26
49
  const current = ++latestLoad;
27
50
  let r;
28
51
  try {
@@ -31,8 +54,17 @@ export async function load(quiet) {
31
54
  toast(GONE);
32
55
  return;
33
56
  }
34
- const next = await r.json();
57
+ const text = await r.text();
35
58
  if (current !== latestLoad) return;
59
+ const body = text.replace(/"now":\d+\}$/, "");
60
+ const same = quiet && body === lastBody && Date.now() - drawnAt < REDRAW_MS;
61
+ lastBody = body;
62
+ if (same) {
63
+ if (!store.all) void refreshBoardBadge();
64
+ return;
65
+ }
66
+ drawnAt = Date.now();
67
+ const next = JSON.parse(text);
36
68
  const was = store.openKey && store.S.cards.find((x) => key(x) === store.openKey);
37
69
  store.S = next;
38
70
  if (!store.all) void refreshBoardBadge();
@@ -89,8 +121,9 @@ export async function load(quiet) {
89
121
  }
90
122
  if (store.openKey) {
91
123
  const c = store.S.cards.find((x) => key(x) === store.openKey),
92
- ta = $("pbody").querySelector(".notes textarea");
93
- if (ta && document.activeElement === ta) return;
124
+ nb = $("pbody").querySelector(".notes");
125
+ // The textarea is hidden under the rich editor: focus anywhere in the notes counts.
126
+ if (nb?.contains(document.activeElement)) return;
94
127
  if (!c) {
95
128
  if (was && was.kind === "idea") follow(was);
96
129
  return;
@@ -18,16 +18,16 @@ export async function resume(c, b) {
18
18
  return;
19
19
  }
20
20
  toast("Resumed, " + where(r) + ": " + via(r.agent));
21
- if (r.pty) store.wantTerm = key(c);
21
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
22
22
  if (store.openKey === key(c)) {
23
23
  $("pfoot").innerHTML = "";
24
24
  openRun(c, true);
25
25
  }
26
26
  }
27
27
  export const APPROVAL = {
28
- "approvals.plan": "Read the plan, then: Approve starts the build; Revise sends it back with what to change.",
29
- "approvals.review": "The work is ready to check. Approve finishes it; Revise sends it back with what to change.",
30
- findings: "The review has open findings. Approve as-is to accept them and finish, or fix selected findings first.",
28
+ "approvals.plan": "Plan ready.",
29
+ "approvals.review": "Ready to check.",
30
+ findings: "Open findings.",
31
31
  },
32
32
  decided = new Set(),
33
33
  answer = (c) => key(c) + ":" + c.awaiting + ":" + c.moved;
@@ -47,8 +47,8 @@ export async function decide(c, b, why, answers) {
47
47
  return;
48
48
  }
49
49
  decided.add(answer(c));
50
- toast((why === undefined ? "Approved" : "Sent back") + ", " + where(r) + ": " + via(r.agent));
51
- if (r.pty) store.wantTerm = key(c);
50
+ toast((why === undefined ? "Approved" : "Sent back") + ", " + (r.reused ? "sent to the agent already open in its card" : where(r) + ": " + via(r.agent)));
51
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
52
52
  if (store.openKey === key(c)) {
53
53
  $("pfoot").innerHTML = "";
54
54
  openRun(c, true);
@@ -14,6 +14,7 @@ export function boardBadge(cards: BadgeCard[], projects?: unknown[], agents?: un
14
14
  }
15
15
 
16
16
  let generation = 0;
17
+ let lastAll = "";
17
18
  let loading = false;
18
19
  let again = false;
19
20
  export async function refreshBoardBadge() {
@@ -25,8 +26,11 @@ export async function refreshBoardBadge() {
25
26
  try {
26
27
  const r = await fetch("/state?all=1");
27
28
  if (!r.ok) continue;
28
- const { cards, projects, rail, agents } = await r.json();
29
- if (!again && current === generation) boardBadge(cards, [...projects, ...(rail ?? [])], agents);
29
+ const text = await r.text();
30
+ const body = text.replace(/"now":\d+\}$/, "");
31
+ if (body === lastAll) continue;
32
+ const { cards, projects, rail, agents } = JSON.parse(text);
33
+ if (!again && current === generation) { lastAll = body; boardBadge(cards, [...projects, ...(rail ?? [])], agents); }
30
34
  } catch { /* keep the last count while the board is offline */ }
31
35
  } while (again);
32
36
  loading = false;
@@ -7,6 +7,7 @@ import { draft, undraft } from "./drafts.ts";
7
7
  import { COLS, ICON, MARKS, NAMES, WORD, age, d, need } from "./labels.ts";
8
8
  import { brief } from "./markdown.ts";
9
9
  import { open, openAt, toggleArchive } from "./panel.ts";
10
+ import { isPhone } from "./phone.ts";
10
11
  import { ideaCombo, list, newDir, plogo, setNewDir, short, showList, showable } from "./projects.ts";
11
12
  import { askNotify, toast } from "./toast.ts";
12
13
  import { answer, decided, resumable, resume } from "./approvals.ts";
@@ -512,7 +513,7 @@ async function startRun(c, kind) {
512
513
  if (r.ok) {
513
514
  toast((kind === "full" ? "Full" : kind === "lite" ? "Lite" : "Started") + (yolo ? " yolo" : "") + " run " + where(r) + ": " + via(r.agent));
514
515
  // A backlog card has no terminal of its own; the run's card gets it once the run exists.
515
- if (r.pty && !backlog) store.wantTerm = key(c);
516
+ if (r.pty && !backlog) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
516
517
  // An idea's run opens in its workspace; the view follows it once the run card exists.
517
518
  if (!backlog) openWorkspace(c);
518
519
  }
@@ -529,7 +530,8 @@ let newFiles = [];
529
530
  // preset to that page's project or empty so one is chosen. The Board keeps its own rule.
530
531
  let formPick: { dir: string | null } | null = null;
531
532
  function ideaForm(f, shut) {
532
- const picking = store.all || !!formPick;
533
+ // A phone has no project picker in its header: the form is the only place to choose.
534
+ const picking = store.all || !!formPick || isPhone();
533
535
  const close = () => {
534
536
  newFiles = [];
535
537
  shut();
@@ -76,7 +76,7 @@ export function fixForm(c) {
76
76
  "Fixing " + nums.length + " finding" + (nums.length === 1 ? "" : "s") + ", " +
77
77
  (r.reused ? "sent to the agent already open in its card" : where(r) + ": " + via(r.agent)),
78
78
  );
79
- if (r.pty) store.wantTerm = key(c);
79
+ if (r.pty) (store.wantTerm = key(c)), (store.wantPty = { key: r.pty, at: Date.now() });
80
80
  nums.forEach((n) => fixSent.add(k(n)));
81
81
  try {
82
82
  sessionStorage.setItem(SK, JSON.stringify([...fixSent]));
package/web/board/git.ts CHANGED
@@ -1,78 +1,399 @@
1
1
  import { store } from "./store.ts";
2
2
  import { post } from "./api.ts";
3
3
  import { key } from "./cards.ts";
4
- import { $, html } 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
- // Commit and push, for a finished run in a project with a git remote. What the board
10
- // did is recorded per run, so the settled label outlives later changes to the tree.
11
- export function gitBtn(c) {
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
+ // project's own checkout (no worktree) only commits and pushes.
14
+
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; shut?: Record<string, boolean> }>();
17
+ const st = (c) => {
18
+ let u = ui.get(key(c));
19
+ if (!u) ui.set(key(c), (u = {}));
20
+ return u;
21
+ };
22
+
23
+ // Commits only after the final approval, and only on a finished run.
24
+ export const gitShown = (c) => {
25
+ const g = store.runDoc && store.runDoc.git;
26
+ return (
27
+ !!(g && g.repo) && !c.archived && c.accept !== "needs" && (c.status === "done" || c.awaiting === "approvals.review")
28
+ );
29
+ };
30
+ // Something is left to do: the footer points at the tab.
31
+ export const gitPending = (c) => {
32
+ if (!gitShown(c)) return false;
12
33
  const g = store.runDoc.git,
13
- k = store.runDoc.commit;
14
- // Done without the user's acceptance: nothing commits until it is approved.
15
- if (c.accept === "needs") return "";
16
- if (c.archived || !g || !g.repo || !(c.status === "done" || c.awaiting === "approvals.review")) return "";
17
- // A run already pushed keeps saying so; work changed since is offered beside it.
18
- if (k && k.pushed)
19
- return (
20
- html`<button class="btn" disabled title="${k.sha}">Committed &amp; pushed</button>` +
21
- (g.files.length
22
- ? `<button class="btn" data-a="commit">Commit new changes</button>`
23
- : g.ahead > 0
24
- ? `<button class="btn" data-a="push">Push</button>`
25
- : "")
26
- );
27
- if (g.files.length) return `<button class="btn pri" data-a="commit">Commit &amp; push</button>`;
28
- if (g.ahead > 0) return `<button class="btn pri" data-a="push">Push</button>`;
29
- // None of its files changed and level with the remote: it was committed and pushed
30
- // somewhere else. With no record and no report, nothing says it was ever committed.
31
- return k || store.runDoc.impl ? `<button class="btn" disabled>Committed &amp; pushed</button>` : "";
34
+ b = store.runDoc.branch;
35
+ return (
36
+ g.files.length > 0 ||
37
+ (b
38
+ ? (b.upstream && g.ahead > 0) ||
39
+ (b.pr && b.pr.state === "OPEN") ||
40
+ (b.landed && !b.pr) ||
41
+ (b.pr && b.pr.state === "MERGED")
42
+ : g.ahead > 0)
43
+ );
44
+ };
45
+
46
+ // Every step, in the order the primary button walks them. `why` is set when the step is
47
+ // unavailable; the menu shows it under the label, as Orca does.
48
+ function steps(c) {
49
+ const g = store.runDoc.git,
50
+ b = store.runDoc.branch,
51
+ pr = b && b.pr,
52
+ files = g.files.length,
53
+ staged = (g.staged || []).length,
54
+ open = pr && pr.state === "OPEN";
55
+ const s = [
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" },
58
+ {
59
+ a: "push",
60
+ label: "Push",
61
+ why: files
62
+ ? "Commit changes first"
63
+ : b && !b.upstream
64
+ ? "Not published yet: Create PR pushes it"
65
+ : g.ahead > 0
66
+ ? ""
67
+ : "Nothing to push",
68
+ },
69
+ ];
70
+ if (!b) return s;
71
+ const noGh = b.gh ? "" : "Needs the GitHub CLI (gh) and a GitHub remote";
72
+ const prWhy =
73
+ noGh ||
74
+ (files
75
+ ? "Commit changes first"
76
+ : pr && pr.state !== "CLOSED"
77
+ ? `Pull request #${pr.number} is ${pr.state === "MERGED" ? "merged" : "open"}`
78
+ : "");
79
+ s.push(
80
+ { a: "pr", label: b.upstream && g.ahead === 0 ? "Create PR" : "Push & create PR", why: prWhy },
81
+ { a: "draft", label: "Create draft PR", why: prWhy },
82
+ {
83
+ a: "merge",
84
+ label: "Merge PR",
85
+ why:
86
+ noGh ||
87
+ (!open
88
+ ? "No open pull request"
89
+ : pr.draft
90
+ ? "Draft: mark it ready on GitHub first"
91
+ : files
92
+ ? "Commit changes first"
93
+ : g.ahead > 0
94
+ ? "Push first"
95
+ : ""),
96
+ },
97
+ {
98
+ a: "remove",
99
+ label: "Remove workspace",
100
+ why: files ? "Commit or discard the changes first" : b.landed ? "" : "Merge the pull request first",
101
+ },
102
+ );
103
+ return s;
32
104
  }
33
- export function confirmCommit(c, msg) {
105
+
106
+ const PR_WORD = { OPEN: "Open", MERGED: "Merged", CLOSED: "Closed" };
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
+
120
+ export function gitTab(c, refresh) {
121
+ const body = $("pbody");
122
+ // A refresh while the user types or a step runs would lose the text or the busy label.
123
+ if (
124
+ refresh &&
125
+ body.querySelector(".gitp") &&
126
+ (body.querySelector(".gitp [data-busy]") || body.querySelector(".gitp")!.contains(document.activeElement))
127
+ )
128
+ return;
34
129
  const g = store.runDoc.git,
35
- foot = $("pfoot");
36
- foot.innerHTML = html`<div class="inl" style="flex:1"><div class="q">Commit ${g.files.length} changed file${g.files.length === 1 ? "" : "s"} on ${g.branch || "this branch"} and push to ${g.remote}?</div><div class="q dim">Only the files this run's report names.${g.others ? ` ${g.others} other changed file${g.others === 1 ? " is" : "s are"} left alone.` : ""}</div><pre class="files">${g.files.join("\n")}</pre>${g.shared && g.shared.length ? html`<div class="q">These files also hold other runs' changes, and a file is committed whole:</div><pre class="files">${g.shared.join("\n")}</pre>` : ""}<textarea aria-label="Commit message" placeholder="Describe what changed">${msg || commitMsg(store.runDoc.impl) || c.title || c.text}</textarea><div class="q dim" id="clong" hidden>The first line is over 72 characters; logs will cut it short.</div><div class="row"><button class="btn ghost" data-a="c">Cancel</button><button class="btn pri" data-a="s">Commit &amp; push</button></div></div>`;
37
- const inp = foot.querySelector("textarea"),
38
- go = foot.querySelector("[data-a=s]");
39
- inp.focus();
40
- // Tall enough to show the whole message, up to half the window.
41
- const fit = () => {
42
- inp.style.height = "auto";
43
- inp.style.height = Math.min(inp.scrollHeight + 2, innerHeight / 2) + "px";
44
- $("clong").hidden = inp.value.split("\n")[0].length <= 72;
45
- };
46
- inp.oninput = fit;
47
- fit();
48
- foot.querySelector("[data-a=c]").onclick = () => {
49
- foot.innerHTML = "";
50
- openRun(c, true);
51
- };
52
- go.onclick = () => {
53
- if (!inp.value.trim()) {
54
- toast("A commit message is required");
55
- return;
56
- }
57
- commitPush(c, inp.value, go);
58
- };
59
- inp.onkeydown = (e) => {
60
- if (e.key === "Enter" && !e.shiftKey) {
61
- e.preventDefault();
62
- go.click();
63
- }
130
+ b = store.runDoc.branch,
131
+ pr = b && b.pr,
132
+ u = st(c),
133
+ all = steps(c),
134
+ rows = g.rows || [],
135
+ staged = rows.filter((r) => r.staged),
136
+ unstaged = rows.filter((r) => !r.staged),
137
+ target = b ? `origin/${b.base}` : `${g.remote}/${g.branch || "HEAD"}`;
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 };
150
+ const chip = pr
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
153
+ >`
154
+ : b && b.checking
155
+ ? html`<span class="gchip dim">Checking PR…</span>`
156
+ : b && b.gh && !all.find((x) => x.a === "pr").why
157
+ ? html`<button class="gchip" data-a="pr"><svg><use href="#t-git" /></svg>Create PR</button>`
158
+ : "";
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>`;
64
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>
203
+ </div>`
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");
207
+ // The inline confirm or form the last click opened, in place of the split button.
208
+ const ask =
209
+ u.ask === "pr" || u.ask === "draft"
210
+ ? html`<div class="gsec gform">
211
+ <div class="ghd">${u.ask === "draft" ? "Draft pull request" : "Pull request"} into ${b.base}</div>
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>
213
+ <div class="row">
214
+ <button class="btn ghost" data-a="cancel">Cancel</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>
216
+ </div>
217
+ </div>`
218
+ : u.ask === "merge"
219
+ ? html`<div class="gsec gform">
220
+ <div class="ghd">Merge #${pr.number} into ${b.base} by rebase?</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>
222
+ </div>`
223
+ : u.ask === "remove"
224
+ ? html`<div class="gsec gform">
225
+ <div class="ghd">Remove the worktree and delete ${b.branch}?</div>
226
+ <div class="dim">Its work is on ${b.base}. The branch is deleted here and on GitHub.</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>
228
+ </div>`
229
+ : "";
230
+ const menu = all
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>`] : []);
233
+ const split = ask
234
+ ? ""
235
+ : html`<div class="split gsplit">
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>
238
+ <div class="menu-pop" role="menu" hidden>${raw(menu.join(""))}</div>
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
+ : "";
254
+ body.innerHTML = html`<div class="gitp">
255
+ <div class="ghead">
256
+ ${chip}
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>
259
+ </div>
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}
264
+ </div>`;
265
+ wire(c, body.querySelector(".gitp"));
266
+ }
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
+
281
+ function wire(c, el) {
282
+ const u = st(c),
283
+ inp = el.querySelector("#gmsg");
284
+ if (inp) {
285
+ const fit = () => {
286
+ inp.style.height = "auto";
287
+ inp.style.height = Math.min(inp.scrollHeight + 2, innerHeight / 2) + "px";
288
+ $("glong").hidden = inp.value.split("\n")[0].length <= 72;
289
+ };
290
+ inp.oninput = () => {
291
+ u.msg = inp.value;
292
+ fit();
293
+ };
294
+ fit();
295
+ }
296
+ el.querySelector("#gtitle")?.addEventListener("input", (e) => (u.title = e.target.value));
297
+ el.querySelector("#gbody")?.addEventListener("input", (e) => (u.body = e.target.value));
298
+ const more = el.querySelector(".gmore"),
299
+ pop = el.querySelector(".gsplit .menu-pop");
300
+ if (more)
301
+ more.onclick = (e) => {
302
+ e.stopPropagation();
303
+ pop.hidden = !pop.hidden;
304
+ if (!pop.hidden) addEventListener("click", () => (pop.hidden = true), { once: true });
305
+ };
306
+ el.querySelectorAll("[data-a]").forEach((b) => {
307
+ if (!b.dataset.a) return;
308
+ b.onclick = () => act(c, b.dataset.a, b);
309
+ });
65
310
  }
66
- export async function commitPush(c, message, b) {
311
+
312
+ const BUSY = {
313
+ commit: "Committing…",
314
+ commitpush: "Pushing…",
315
+ push: "Pushing…",
316
+ "go-pr": "Creating PR…",
317
+ "go-draft": "Creating PR…",
318
+ "go-merge": "Merging…",
319
+ "go-remove": "Removing…",
320
+ };
321
+
322
+ async function act(c, a, b) {
323
+ const u = st(c);
324
+ if (a === "cancel") return ((u.ask = undefined), gitTab(c, false));
325
+ // Steps that need a second look open their form or confirm first.
326
+ if (a === "pr" || a === "draft" || a === "merge" || a === "remove") return ((u.ask = a), gitTab(c, false));
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");
67
364
  b.disabled = true;
68
365
  b.dataset.busy = 1;
69
- b.textContent = "Pushing…";
70
- const r = await post("/commit", { dir: c.state, id: c.id, message, files: store.runDoc.git.files });
71
- if (r.ok) toast("Committed & pushed " + r.sha);
72
- $("pfoot").innerHTML = "";
366
+ b.textContent = BUSY[a] || "Working…";
367
+ const base = { dir: c.state, id: c.id };
368
+ const r =
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 })
373
+ : a === "go-pr" || a === "go-draft"
374
+ ? await post("/pr", {
375
+ ...base,
376
+ op: "create",
377
+ title: u.title ?? $("gtitle").value,
378
+ body: u.body ?? $("gbody").value,
379
+ draft: a === "go-draft",
380
+ })
381
+ : await post("/pr", { ...base, op: a === "go-merge" ? "merge" : "remove" });
382
+ if (r.ok) {
383
+ toast(
384
+ a === "commit"
385
+ ? "Committed " + r.sha
386
+ : a === "commitpush" || a === "push"
387
+ ? "Committed & pushed " + r.sha
388
+ : a === "go-merge"
389
+ ? "Merged"
390
+ : a === "go-remove"
391
+ ? "Worktree removed"
392
+ : "Pull request #" + r.pr.number + " opened",
393
+ );
394
+ ui.delete(key(c));
395
+ }
73
396
  if (store.openKey !== key(c)) return;
397
+ delete b.dataset.busy;
74
398
  await openRun(c, false);
75
- // A refused message comes back for another try, beside the current file list.
76
- if (!r.ok && message && store.openKey === key(c) && store.runDoc.git.files && store.runDoc.git.files.length)
77
- confirmCommit(c, message);
78
399
  }
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);