kaizen-agent 1.79.1 → 1.80.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/cli/hermes.ts +20 -0
- package/cli/install.ts +20 -1
- package/cli/localsend.ts +61 -4
- package/cli/report.ts +7 -4
- package/cli/settings.ts +2 -8
- package/cli/state.ts +19 -3
- package/cli/task-results.ts +133 -0
- package/cli/task-service.ts +180 -0
- package/cli/tasks.ts +201 -0
- package/cli/ui-audit.allow.json +6 -0
- package/cli/ui-audit.ts +427 -0
- package/cli/web.ts +72 -1
- package/cli/whatsapp.ts +112 -0
- package/package.json +2 -1
- package/skills/kaizen/SKILL.md +4 -0
- package/skills/kaizen/adapters.md +4 -0
- package/skills/kaizen/spec-build.md +5 -1
- package/skills/kaizen/spec-main.md +4 -0
- package/skills/kaizen/spec-plan.md +4 -0
- package/skills/kaizen/spec-review.md +4 -0
- package/skills/kaizen/spec.md +52 -0
- package/web/board/add-project.ts +1 -1
- package/web/board/badge.ts +70 -8
- package/web/board/cards.ts +4 -2
- package/web/board/dom.ts +10 -0
- package/web/board/icebox.ts +2 -2
- package/web/board/keys.ts +1 -1
- package/web/board/live.ts +9 -5
- package/web/board/phone.ts +4 -3
- package/web/board/rich.ts +4 -2
- package/web/board/run-view.ts +16 -14
- package/web/board/settings-automations.ts +2 -2
- package/web/board/settings-skills.ts +2 -2
- package/web/board/settings.ts +12 -14
- package/web/board/task-page.ts +672 -0
- package/web/board/task-results.ts +235 -0
- package/web/board/tasks.ts +214 -200
- package/web/board/terms.ts +17 -2
- package/web/board/views.ts +35 -9
- package/web/board/whatsapp-setup.ts +137 -0
- package/web/board/workspace.ts +24 -2
- package/web/board.html +57 -35
- package/web/board.js +403 -142
- package/web/notebook.js +388 -153
- package/web/notes.html +16 -11
- package/web/term.js +1 -1
- package/web/video.html +22 -11
- package/web/video.js +415 -180
- package/web/video.ts +5 -5
- package/web/board/new-agent.ts +0 -20
package/cli/ui-audit.ts
ADDED
|
@@ -0,0 +1,427 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
// Measured alignment audit of the web board: `bun run audit:ui`. A dev tool, not a kaizen
|
|
3
|
+
// command. It starts a scratch board (copied runs, its own HOME and port, so no real state is
|
|
4
|
+
// touched), drives headless Chromium over CDP through every screen and open state, in light and
|
|
5
|
+
// dark at 1400px and 400px, and measures with getBoundingClientRect instead of by eye:
|
|
6
|
+
// row controls in one centred row whose visible content sits off the row's centre
|
|
7
|
+
// column stacked siblings whose left edges differ from the majority by 1-4px
|
|
8
|
+
// size one component class (.btn, .ib, .chk, .sel …) drawn at two heights on one screen
|
|
9
|
+
// bars top bars side by side whose first rows do not share a centre
|
|
10
|
+
// Exceptions live in ui-audit.allow.json, each with a reason. Output: <out>/report.md and a
|
|
11
|
+
// screenshot per flagged screen with the flagged boxes outlined.
|
|
12
|
+
//
|
|
13
|
+
// bun run audit:ui [--out DIR] [--only NAME[,NAME]] [--from PROJECT] [--port N] [--shots] [--keep]
|
|
14
|
+
// --shots saves a screenshot of every state, flagged or not; --keep leaves the scratch folder.
|
|
15
|
+
import { cpSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
|
|
16
|
+
import { tmpdir } from "node:os";
|
|
17
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
18
|
+
import { findBrowser, Page } from "./browser.ts";
|
|
19
|
+
|
|
20
|
+
const repo = resolve(import.meta.dir, "..");
|
|
21
|
+
const nap = (ms: number) => new Promise((r) => setTimeout(r, ms));
|
|
22
|
+
|
|
23
|
+
// ---- what is measured, in the page. Kept as one function so the fixture test runs the same code.
|
|
24
|
+
export type Flag = { rule: "row" | "column" | "size" | "bars"; path: string; px: number; box: [number, number, number, number]; note: string };
|
|
25
|
+
|
|
26
|
+
// Runs in the page; returns the flags. No closure over anything outside it.
|
|
27
|
+
export function measure(bars: string[][], variants: string[] = []): Flag[] {
|
|
28
|
+
const out: Flag[] = [];
|
|
29
|
+
const vw = innerWidth, vh = innerHeight;
|
|
30
|
+
const cs = (e: Element) => getComputedStyle(e);
|
|
31
|
+
const shown = (e: Element) => {
|
|
32
|
+
const r = e.getBoundingClientRect();
|
|
33
|
+
if (r.width <= 1 || r.height <= 1 || r.bottom <= 0 || r.right <= 0 || r.top >= vh || r.left >= vw) return false;
|
|
34
|
+
// Also false inside a closed <details>, whose content keeps its boxes but is not drawn.
|
|
35
|
+
return e.checkVisibility({ opacityProperty: true, visibilityProperty: true, contentVisibilityAuto: true });
|
|
36
|
+
};
|
|
37
|
+
const inFlow = (e: Element) => { const p = cs(e).position; return p !== "absolute" && p !== "fixed"; };
|
|
38
|
+
const path = (e: Element) => {
|
|
39
|
+
const bits: string[] = [];
|
|
40
|
+
for (let n: Element | null = e; n && n !== document.body && bits.length < 4; n = n.parentElement) {
|
|
41
|
+
const cls = [...n.classList].filter((c) => !/^(on|open|sel|active|cur|hot|ro|split)$/.test(c)).slice(0, 2);
|
|
42
|
+
bits.unshift(n.tagName.toLowerCase() + (n.id ? "#" + n.id : "") + (cls.length ? "." + cls.join(".") : ""));
|
|
43
|
+
if (n.id) break;
|
|
44
|
+
}
|
|
45
|
+
return bits.join(">");
|
|
46
|
+
};
|
|
47
|
+
const box = (r: DOMRect): [number, number, number, number] => [Math.round(r.left), Math.round(r.top), Math.round(r.width), Math.round(r.height)];
|
|
48
|
+
// What the eye sees of an element: the union of its glyphs, icons, images and form controls.
|
|
49
|
+
// An icon counts by its box, as icons are drawn centred in their viewBox and laid out by it.
|
|
50
|
+
const ink = (e: Element): DOMRect | null => {
|
|
51
|
+
let l = Infinity, t = Infinity, r = -Infinity, b = -Infinity;
|
|
52
|
+
const add = (q: DOMRect) => { if (q.width < 1 || q.height < 1) return; l = Math.min(l, q.left); t = Math.min(t, q.top); r = Math.max(r, q.right); b = Math.max(b, q.bottom); };
|
|
53
|
+
const walk = (n: Node) => {
|
|
54
|
+
if (n.nodeType === 3) {
|
|
55
|
+
if (!n.textContent!.trim()) return;
|
|
56
|
+
const g = document.createRange(); g.selectNodeContents(n);
|
|
57
|
+
for (const q of g.getClientRects()) add(q);
|
|
58
|
+
return;
|
|
59
|
+
}
|
|
60
|
+
if (n.nodeType !== 1) return;
|
|
61
|
+
const el = n as Element;
|
|
62
|
+
if (!shown(el)) return;
|
|
63
|
+
// Not part of the row as drawn: a closed <details> beyond its summary, or a popup laid over it.
|
|
64
|
+
if (el.parentElement?.tagName === "DETAILS" && !(el.parentElement as HTMLDetailsElement).open && el.tagName !== "SUMMARY") return;
|
|
65
|
+
if (el !== e && !inFlow(el)) return;
|
|
66
|
+
const tag = el.tagName;
|
|
67
|
+
const s = cs(el);
|
|
68
|
+
// A drawn thing with its own box: an icon, an image, a control, or a box with a visible border, ring or fill.
|
|
69
|
+
const filled = s.backgroundColor !== "rgba(0, 0, 0, 0)" && s.backgroundColor !== "transparent";
|
|
70
|
+
const bordered = (parseFloat(s.borderTopWidth) > 0 && parseFloat(s.borderBottomWidth) > 0 && s.borderTopStyle !== "none") || s.boxShadow !== "none";
|
|
71
|
+
if (tag === "svg" || tag === "IMG" || tag === "INPUT" || tag === "SELECT" || tag === "TEXTAREA" || tag === "CANVAS" || tag === "VIDEO" || filled || bordered) {
|
|
72
|
+
return add(el.getBoundingClientRect());
|
|
73
|
+
}
|
|
74
|
+
for (const c of el.childNodes) walk(c);
|
|
75
|
+
};
|
|
76
|
+
walk(e);
|
|
77
|
+
return l === Infinity ? null : new DOMRect(l, t, r - l, b - t);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const all = [...document.body.querySelectorAll("*")].filter((e) => !e.closest("svg") || e.tagName === "svg");
|
|
81
|
+
for (const el of all) {
|
|
82
|
+
if (!shown(el)) continue;
|
|
83
|
+
const s = cs(el);
|
|
84
|
+
const kids = [...el.children].filter((c) => shown(c) && inFlow(c) && c.tagName !== "BR");
|
|
85
|
+
if (kids.length < 2) continue;
|
|
86
|
+
const flexRow = (s.display.includes("flex") && !s.flexDirection.startsWith("column")) || (s.display.includes("grid") && s.gridAutoFlow.startsWith("column"));
|
|
87
|
+
// ---- row: the row's line is the median of its children's box centres; each child's ink must sit on it.
|
|
88
|
+
if (flexRow && s.alignItems === "center") {
|
|
89
|
+
const lines: Element[][] = [];
|
|
90
|
+
for (const k of kids) {
|
|
91
|
+
const r = k.getBoundingClientRect();
|
|
92
|
+
const line = lines.find((ln) => { const q = ln[0]!.getBoundingClientRect(); return r.top < q.bottom && r.bottom > q.top; });
|
|
93
|
+
line ? line.push(k) : lines.push([k]);
|
|
94
|
+
}
|
|
95
|
+
for (const ln of lines) {
|
|
96
|
+
if (ln.length < 2) continue;
|
|
97
|
+
const mids = ln.map((k) => { const r = k.getBoundingClientRect(); return r.top + r.height / 2; }).sort((a, b) => a - b);
|
|
98
|
+
const line = mids[Math.floor(mids.length / 2)]!;
|
|
99
|
+
for (const k of ln) {
|
|
100
|
+
const i = ink(k);
|
|
101
|
+
// A block over 48px tall (lines of text, a card) is judged by its box, which the row centres.
|
|
102
|
+
if (!i || i.height > 48) continue;
|
|
103
|
+
const d = i.top + i.height / 2 - line;
|
|
104
|
+
if (Math.abs(d) >= 1) out.push({ rule: "row", path: path(k), px: Math.round(d * 10) / 10, box: box(i), note: "centre off the row by" });
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
// ---- column: stacked siblings, the ink's left edge against the majority.
|
|
109
|
+
const stacked = kids.every((k, j) => j === 0 || k.getBoundingClientRect().top >= kids[j - 1]!.getBoundingClientRect().bottom - 1);
|
|
110
|
+
if (stacked && kids.length >= 3) {
|
|
111
|
+
const lefts = kids.map((k) => ink(k)?.left ?? null);
|
|
112
|
+
const count = new Map<number, number>();
|
|
113
|
+
for (const v of lefts) if (v !== null) count.set(Math.round(v), (count.get(Math.round(v)) ?? 0) + 1);
|
|
114
|
+
const [mode, n] = [...count].sort((a, b) => b[1] - a[1])[0] ?? [0, 0];
|
|
115
|
+
if (n >= 2) kids.forEach((k, j) => {
|
|
116
|
+
const v = lefts[j];
|
|
117
|
+
if (v === null || v === undefined) return;
|
|
118
|
+
const d = v - mode;
|
|
119
|
+
if (Math.abs(d) >= 1 && Math.abs(d) <= 4) out.push({ rule: "column", path: path(k), px: Math.round(d * 10) / 10, box: box(ink(k)!), note: "left edge off the column by" });
|
|
120
|
+
});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// ---- size: one component, one height on a screen.
|
|
125
|
+
const kinds: [string, (e: Element) => string | null][] = [
|
|
126
|
+
["btn", (e) => e.classList.contains("btn") ? "btn" + [...e.classList].filter((c) => c !== "btn" && /^(sm|xs|lg|ghost|pri|primary|danger|icon|wide)$/.test(c)).sort().map((c) => "." + c).join("") : null],
|
|
127
|
+
["ib", (e) => e.classList.contains("ib") ? "ib" + [...e.classList].filter((c) => /^(xs|sm|lg)$/.test(c)).sort().map((c) => "." + c).join("") : null],
|
|
128
|
+
["chk", (e) => e.classList.contains("chk") ? (e.classList.contains("sm") ? "chk.sm" : "chk") : null],
|
|
129
|
+
["sel", (e) => e.classList.contains("sel") && e.tagName !== "TEXTAREA" ? "sel" : null],
|
|
130
|
+
];
|
|
131
|
+
const sizes = new Map<string, Map<number, Element[]>>();
|
|
132
|
+
for (const el of document.querySelectorAll(".btn,.ib,.chk,.sel")) {
|
|
133
|
+
if (!shown(el)) continue;
|
|
134
|
+
for (const [, sig] of kinds) {
|
|
135
|
+
const s0 = sig(el);
|
|
136
|
+
if (!s0) continue;
|
|
137
|
+
// A deliberate compact or large group (ui-audit.allow.json "variant") is sized against itself only.
|
|
138
|
+
const v = variants.find((q) => el.matches(q));
|
|
139
|
+
const k = v ? `${s0} in ${v}` : s0;
|
|
140
|
+
const h = Math.round(el.getBoundingClientRect().height);
|
|
141
|
+
const m = sizes.get(k) ?? new Map();
|
|
142
|
+
sizes.set(k, m);
|
|
143
|
+
m.set(h, [...(m.get(h) ?? []), el]);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
for (const [k, m] of sizes) {
|
|
147
|
+
if (m.size < 2) continue;
|
|
148
|
+
const major = [...m].sort((a, b) => b[1].length - a[1].length)[0]![0];
|
|
149
|
+
for (const [h, els] of m) if (h !== major) for (const el of els) out.push({ rule: "size", path: path(el), px: h - major, box: box(el.getBoundingClientRect()), note: `.${k} height ${h}px, most are ${major}px; off by` });
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// ---- bars: groups of top bars that sit side by side; their first rows share a centre.
|
|
153
|
+
const firstRow = (bar: Element) => {
|
|
154
|
+
const leaves = [...bar.querySelectorAll("button,a,summary,select,input,h1,h2,h3,svg,span,b,small,label,pre")]
|
|
155
|
+
.filter((e) => shown(e) && !e.closest("svg:not(:scope)") && !(e.tagName !== "svg" && e.querySelector("button,a,summary,select,input,svg,span,b,small,label")));
|
|
156
|
+
const rects = leaves.map((e) => ink(e)).filter((r): r is DOMRect => !!r);
|
|
157
|
+
if (!rects.length) return null;
|
|
158
|
+
const top = Math.min(...rects.map((r) => r.top));
|
|
159
|
+
const row = rects.filter((r) => r.top < top + Math.min(...rects.filter((q) => q.top === top).map((q) => q.height)));
|
|
160
|
+
const mids = row.map((r) => r.top + r.height / 2).sort((a, b) => a - b);
|
|
161
|
+
return mids[Math.floor(mids.length / 2)]!;
|
|
162
|
+
};
|
|
163
|
+
for (const group of bars) {
|
|
164
|
+
const found = group.map((sel) => [sel, document.querySelector(sel)] as const).filter(([, e]) => e && shown(e)) as [string, Element][];
|
|
165
|
+
if (found.length < 2) continue;
|
|
166
|
+
const ref = firstRow(found[0]![1]);
|
|
167
|
+
if (ref === null) continue;
|
|
168
|
+
const a = found[0]![1].getBoundingClientRect();
|
|
169
|
+
for (const [sel, e] of found.slice(1)) {
|
|
170
|
+
// Only bars side by side: they share some height and none of their width (a phone stacks them).
|
|
171
|
+
const b = e.getBoundingClientRect();
|
|
172
|
+
if (b.top >= a.bottom || b.bottom <= a.top || (b.left < a.right && b.right > a.left)) continue;
|
|
173
|
+
const c = firstRow(e);
|
|
174
|
+
if (c === null) continue;
|
|
175
|
+
const d = c - ref;
|
|
176
|
+
if (Math.abs(d) >= 1) out.push({ rule: "bars", path: sel, px: Math.round(d * 10) / 10, box: box(e.getBoundingClientRect()), note: `first row centre ${Math.round(c)}px against ${found[0]![0]} at ${Math.round(ref)}px; off by` });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return out;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// ---- the scratch board and the browser
|
|
183
|
+
const arg = (name: string, dflt = "") => { const i = Bun.argv.indexOf(name); return i > 0 ? Bun.argv[i + 1] ?? dflt : dflt; };
|
|
184
|
+
|
|
185
|
+
// A project to copy runs from: --from, else the main checkout this worktree belongs to, else this one.
|
|
186
|
+
export function sourceProject(): string {
|
|
187
|
+
const f = arg("--from");
|
|
188
|
+
if (f) return resolve(f);
|
|
189
|
+
const g = Bun.spawnSync(["git", "rev-parse", "--path-format=absolute", "--git-common-dir"], { cwd: repo });
|
|
190
|
+
const main = g.exitCode === 0 ? dirname(g.stdout.toString().trim()) : repo;
|
|
191
|
+
return existsSync(join(main, ".kaizen", "runs")) ? main : repo;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
// Copies the project's .kaizen without worktrees, attachments or big files, and only the newest runs.
|
|
195
|
+
export function scratchProject(root: string, from: string): string {
|
|
196
|
+
const dst = join(root, "project");
|
|
197
|
+
const src = join(from, ".kaizen");
|
|
198
|
+
mkdirSync(join(dst, ".kaizen", "runs"), { recursive: true });
|
|
199
|
+
// A repository with one commit: the board offers New workspace and shows a branch only in one.
|
|
200
|
+
const git = (...a: string[]) => Bun.spawnSync(["git", "-c", "user.name=ui-audit", "-c", "user.email=ui-audit@localhost", ...a], { cwd: dst });
|
|
201
|
+
git("init", "-q", "-b", "main");
|
|
202
|
+
git("commit", "-q", "--allow-empty", "-m", "scratch");
|
|
203
|
+
if (!existsSync(src)) return dst;
|
|
204
|
+
const small = (p: string) => { const s = statSync(p); return s.isDirectory() ? !/[\\/](attachments|wt|sessions)$/.test(p) : s.size < 512_000; };
|
|
205
|
+
for (const f of readdirSync(src)) if (!["runs", "wt", "sessions", "attachments", "automations.json"].includes(f) && small(join(src, f))) cpSync(join(src, f), join(dst, ".kaizen", f), { recursive: true, filter: small });
|
|
206
|
+
const runs = existsSync(join(src, "runs")) ? readdirSync(join(src, "runs")).sort().slice(-40) : [];
|
|
207
|
+
const live = /[\\/](terminals|handoff|workers)\.json$/;
|
|
208
|
+
for (const r of runs) {
|
|
209
|
+
const to = join(dst, ".kaizen", "runs", r);
|
|
210
|
+
cpSync(join(src, "runs", r), to, { recursive: true, filter: (p) => small(p) && !live.test(p) });
|
|
211
|
+
// A copied run points at nothing real: no worktree, branch or agent session of the source project.
|
|
212
|
+
const sf = join(to, "state.json");
|
|
213
|
+
try {
|
|
214
|
+
const s = JSON.parse(readFileSync(sf, "utf8"));
|
|
215
|
+
for (const k of ["worktree", "branch", "session", "base_branch", "base_sha", "workspace"]) delete s[k];
|
|
216
|
+
writeFileSync(sf, JSON.stringify(s));
|
|
217
|
+
} catch { /* no state: the board shows it as it is */ }
|
|
218
|
+
}
|
|
219
|
+
return dst;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export async function startBoard(root: string, project: string, port: number) {
|
|
223
|
+
const home = join(root, "home");
|
|
224
|
+
mkdirSync(join(home, ".kaizen"), { recursive: true });
|
|
225
|
+
writeFileSync(join(home, ".kaizen", "projects"), project + "\n");
|
|
226
|
+
writeFileSync(join(home, ".kaizen", "onboarding.json"), JSON.stringify({ step: 0, outcome: "done" }) + "\n");
|
|
227
|
+
const env = { ...process.env, HOME: home, USERPROFILE: home } as Record<string, string>;
|
|
228
|
+
delete env.KAIZEN_HOME;
|
|
229
|
+
const log = Bun.file(join(root, "board.log"));
|
|
230
|
+
const proc = Bun.spawn([process.execPath, join(repo, "cli", "install.ts"), "web", "--port", String(port), "--no-open", "--foreground"], { cwd: project, env, stdout: log, stderr: log });
|
|
231
|
+
for (let i = 0; i < 150; i++) {
|
|
232
|
+
await nap(200);
|
|
233
|
+
try { if ((await fetch(`http://127.0.0.1:${port}/`)).ok) return proc; } catch { /* not yet */ }
|
|
234
|
+
if (proc.exitCode !== null) break;
|
|
235
|
+
}
|
|
236
|
+
proc.kill();
|
|
237
|
+
throw new Error(`The scratch board did not start on port ${port}; see ${join(root, "board.log")}`);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
export async function startBrowser(root: string) {
|
|
241
|
+
const exe = findBrowser();
|
|
242
|
+
if (!exe) throw new Error("No Chrome or Chromium found.");
|
|
243
|
+
const prof = join(root, "chrome");
|
|
244
|
+
mkdirSync(prof, { recursive: true });
|
|
245
|
+
// --no-sandbox only on CI, whose runners can refuse Chrome the namespaces its sandbox needs.
|
|
246
|
+
const proc = Bun.spawn([exe, "--headless=new", `--user-data-dir=${prof}`, "--remote-debugging-address=127.0.0.1", "--remote-debugging-port=0",
|
|
247
|
+
"--no-first-run", "--no-default-browser-check", "--hide-scrollbars", ...(process.env.CI ? ["--no-sandbox"] : []), "--font-render-hinting=none", "--force-device-scale-factor=1", "--window-size=1400,900", "about:blank"],
|
|
248
|
+
{ env: process.env, stdout: "ignore", stderr: "ignore" });
|
|
249
|
+
let port = "";
|
|
250
|
+
for (let i = 0; i < 300 && !port; i++) {
|
|
251
|
+
await nap(100);
|
|
252
|
+
try { port = readFileSync(join(prof, "DevToolsActivePort"), "utf8").split("\n")[0]!.trim(); } catch { /* not yet */ }
|
|
253
|
+
}
|
|
254
|
+
if (!port) { proc.kill(); throw new Error("The browser did not start."); }
|
|
255
|
+
const tab = ((await (await fetch(`http://127.0.0.1:${port}/json/list`)).json()) as any[]).find((t) => t.type === "page");
|
|
256
|
+
const page = await Page.open(tab.webSocketDebuggerUrl);
|
|
257
|
+
await page.call("Page.enable");
|
|
258
|
+
await page.call("Runtime.enable");
|
|
259
|
+
return { proc, page };
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
export async function view(page: Page, width: number, dark: boolean) {
|
|
263
|
+
await page.call("Emulation.setDeviceMetricsOverride", { width, height: 900, deviceScaleFactor: 1, mobile: width <= 640 });
|
|
264
|
+
await page.call("Emulation.setEmulatedMedia", { features: [{ name: "prefers-color-scheme", value: dark ? "dark" : "light" }, { name: "prefers-reduced-motion", value: "reduce" }] });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// Waits for the page to stop moving: no running animations and no layout change for 300ms.
|
|
268
|
+
export async function settle(page: Page, ms = 6000) {
|
|
269
|
+
const end = Date.now() + ms;
|
|
270
|
+
let last = "";
|
|
271
|
+
while (Date.now() < end) {
|
|
272
|
+
await nap(300);
|
|
273
|
+
const now = await page.js<string>(`document.readyState + document.getAnimations().filter(a => a.playState === "running" && isFinite(a.effect?.getTiming?.().iterations ?? 1)).length + ":" + document.body.getBoundingClientRect().height + ":" + document.querySelectorAll("*").length`);
|
|
274
|
+
if (now === last && now.startsWith("complete0")) return;
|
|
275
|
+
last = now;
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// ---- screens and states. `open` runs in the page after load: click() waits for a shown element, then clicks it.
|
|
280
|
+
type Screen = { name: string; url: string; widths?: number[]; open?: string };
|
|
281
|
+
const BARS = [[".rail .top", ".hdr", "#rbar", "#panel>header", ".pstrip"], ["#sback", "#smain h2"]];
|
|
282
|
+
const SETTINGS = ["agents", "accounts", "orchestration", "skills", "voice", "general", "integrations", "mobile", "approvals", "autofix", "automations", "git", "terminal", "appearance", "notifications", "shortcuts"];
|
|
283
|
+
|
|
284
|
+
function screens(dir: string, run: string, emptyWs: { dir: string; ws: string }): Screen[] {
|
|
285
|
+
const D = encodeURIComponent(dir);
|
|
286
|
+
const RUN = `/?view=run&dir=${D}&id=${encodeURIComponent(run)}`;
|
|
287
|
+
const EMPTY = `/?view=ws&dir=${encodeURIComponent(emptyWs.dir)}&ws=${encodeURIComponent(emptyWs.ws)}`;
|
|
288
|
+
const D1 = [1400], P = [400];
|
|
289
|
+
return [
|
|
290
|
+
{ name: "board", url: "/?view=board", widths: D1 }, // a phone shows Home for the board
|
|
291
|
+
{ name: "board-runs", url: "/?view=board", widths: D1, open: `await click("[data-m=runs]")` },
|
|
292
|
+
{ name: "card-menu", url: "/?view=board", widths: D1, open: `await click("[data-m=runs]"); await click("[data-a=menu]", true)` },
|
|
293
|
+
{ name: "card-drawer", url: "/?view=board", widths: D1, open: `await click("[data-m=runs]"); await click("main#board>section:last-of-type li .card")` },
|
|
294
|
+
{ name: "projects-filter", url: "/?view=board", widths: D1, open: `await click("#proj")` },
|
|
295
|
+
{ name: "showing", url: "/?view=board", widths: D1, open: `await click("#show")` },
|
|
296
|
+
{ name: "new-task", url: "/?view=board", widths: D1, open: `await click("#newtop")` },
|
|
297
|
+
{ name: "add-project", url: "/?view=board", widths: D1, open: `await click("#padd")` },
|
|
298
|
+
{ name: "new-workspace", url: "/?view=board", widths: D1, open: `await click("#padd"); await click("[data-go=ws]")` },
|
|
299
|
+
{ name: "tasks", url: "/?view=tasks" },
|
|
300
|
+
{ name: "run-form", url: "/?view=tasks", widths: D1, open: `await click(".go[data-i]", false, "Start")` },
|
|
301
|
+
{ name: "icebox", url: "/?view=icebox" },
|
|
302
|
+
{ name: "home", url: "/" },
|
|
303
|
+
{ name: "chat", url: "/?view=chat", widths: P },
|
|
304
|
+
{ name: "terminal", url: "/?view=terminal" },
|
|
305
|
+
{ name: "notes", url: "/notebook" },
|
|
306
|
+
{ name: "video", url: "/video" },
|
|
307
|
+
...SETTINGS.map((p) => ({ name: "settings-" + p, url: "/?view=settings&page=" + p })),
|
|
308
|
+
{ name: "run", url: RUN },
|
|
309
|
+
{ name: "run-none", url: EMPTY, widths: D1 },
|
|
310
|
+
{ name: "run-plus", url: RUN, widths: D1, open: `await click("#rtabs details.radd:not(.rsplit) > summary")` },
|
|
311
|
+
{ name: "run-split", url: RUN, widths: D1, open: `await click("#rtabs details.rsplit > summary")` },
|
|
312
|
+
{ name: "run-picker", url: RUN, widths: D1, open: `await click("#ppick")` },
|
|
313
|
+
{ name: "run-history", url: RUN, widths: D1, open: `await click("#rtabs details.radd:not(.rsplit) > summary"); await click("[data-n=history]")` },
|
|
314
|
+
{ name: "phone-runs", url: "/?view=device", widths: P },
|
|
315
|
+
{ name: "phone-new", url: "/", widths: P, open: `await click("#phome .pag-new")` },
|
|
316
|
+
];
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
const PRELUDE = `const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
320
|
+
const until = async (s, ms = 6000) => { const end = Date.now() + ms; for (;;) { const e = [...document.querySelectorAll(s)].find((x) => x.checkVisibility() && x.getBoundingClientRect().width > 0); if (e) return e; if (Date.now() > end) throw new Error("not found: " + s); await sleep(150); } };
|
|
321
|
+
// force: the element may be drawn only on hover; text: the first match whose text starts with it.
|
|
322
|
+
const click = async (s, force = false, text = "") => {
|
|
323
|
+
const e = force ? document.querySelector(s) : text ? [...document.querySelectorAll(s)].find((x) => x.textContent.trim().startsWith(text)) : await until(s);
|
|
324
|
+
if (!e) throw new Error("not found: " + s + (text ? " " + text : ""));
|
|
325
|
+
e.scrollIntoView({ block: "nearest" }); e.click(); await sleep(400);
|
|
326
|
+
};`;
|
|
327
|
+
|
|
328
|
+
type Hit = Flag & { screen: string; at: string };
|
|
329
|
+
// path + rule: a flag to accept. variant: a selector whose controls form their own size group.
|
|
330
|
+
type Allow = { screen?: string; path?: string; rule?: string; variant?: string; reason: string };
|
|
331
|
+
|
|
332
|
+
const allowed = (h: Hit, allow: Allow[]) => allow.find((a) => a.path && (!a.screen || a.screen === h.screen || (a.screen.endsWith("*") && h.screen.startsWith(a.screen.slice(0, -1)))) && a.rule === h.rule && h.path.includes(a.path));
|
|
333
|
+
|
|
334
|
+
// Draws each flagged box on the page, takes a screenshot, and removes the boxes.
|
|
335
|
+
async function outlined(page: Page, flags: Flag[], file: string) {
|
|
336
|
+
await page.js(`(() => { for (const [x, y, w, h] of ${JSON.stringify(flags.map((f) => f.box))}) { const d = document.createElement("div"); d.className = "kz-audit-box"; d.style.cssText = "position:fixed;z-index:2147483647;pointer-events:none;outline:2px solid #f0f;left:" + (x - 2) + "px;top:" + (y - 2) + "px;width:" + (w + 4) + "px;height:" + (h + 4) + "px"; document.body.append(d); } })()`);
|
|
337
|
+
const r = await page.call("Page.captureScreenshot", { format: "png" });
|
|
338
|
+
await Bun.write(file, Buffer.from(r.data, "base64"));
|
|
339
|
+
await page.js(`document.querySelectorAll(".kz-audit-box").forEach((d) => d.remove())`);
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
export async function audit(base: string, list: Screen[], out: string, page: Page, allow: Allow[], shots = false) {
|
|
343
|
+
const variants = allow.flatMap((a) => (a.variant ? [a.variant] : []));
|
|
344
|
+
const hits: Hit[] = [];
|
|
345
|
+
const broken: string[] = [];
|
|
346
|
+
for (const s of list) for (const width of s.widths ?? [1400, 400]) for (const dark of [false, true]) {
|
|
347
|
+
const at = `${dark ? "dark" : "light"} ${width}`;
|
|
348
|
+
await view(page, width, dark);
|
|
349
|
+
// Each state starts from a clean browser: no board mode, filter or theme left by the one before.
|
|
350
|
+
await page.call("Storage.clearDataForOrigin", { origin: base, storageTypes: "local_storage,session_storage" });
|
|
351
|
+
await page.call("Page.navigate", { url: base + s.url });
|
|
352
|
+
await settle(page);
|
|
353
|
+
if (s.open) {
|
|
354
|
+
const r = await page.call("Runtime.evaluate", { expression: `(async () => { ${PRELUDE}\n${s.open} })()`, awaitPromise: true, returnByValue: true });
|
|
355
|
+
if (r.exceptionDetails) { broken.push(`${s.name} (${at}): ${r.exceptionDetails.exception?.description?.split("\n")[0] ?? r.exceptionDetails.text}`); continue; }
|
|
356
|
+
await settle(page);
|
|
357
|
+
}
|
|
358
|
+
const r = await page.call("Runtime.evaluate", { expression: `(${measure.toString()})(${JSON.stringify(BARS)}, ${JSON.stringify(variants)})`, returnByValue: true });
|
|
359
|
+
if (r.exceptionDetails) { broken.push(`${s.name} (${at}): measure threw ${r.exceptionDetails.exception?.description?.split("\n")[0]}`); continue; }
|
|
360
|
+
const flags: Flag[] = r.result.value ?? [];
|
|
361
|
+
const open = flags.filter((f) => !allowed({ ...f, screen: s.name, at }, allow));
|
|
362
|
+
if (open.length || shots) await outlined(page, open, join(out, `${s.name}-${dark ? "dark" : "light"}-${width}.png`));
|
|
363
|
+
for (const f of flags) hits.push({ ...f, screen: s.name, at });
|
|
364
|
+
console.log(`${s.name.padEnd(24)} ${at.padEnd(11)} ${open.length} flagged${flags.length - open.length ? `, ${flags.length - open.length} allowed` : ""}`);
|
|
365
|
+
}
|
|
366
|
+
return { hits, broken };
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// One line per finding; the same offset in several themes or widths is one line naming them.
|
|
370
|
+
export function report(hits: Hit[], broken: string[], allow: Allow[], screensRun: number): { text: string; flagged: number } {
|
|
371
|
+
const group = new Map<string, Hit[]>();
|
|
372
|
+
// The same offset on the same element is one line, naming every screen and state it shows on.
|
|
373
|
+
for (const h of hits) { const k = [allowed(h, allow)?.reason ?? "", h.rule, h.path, h.px].join("|"); group.set(k, [...(group.get(k) ?? []), h]); }
|
|
374
|
+
const lines: string[] = [], ok: string[] = [];
|
|
375
|
+
for (const hs of group.values()) {
|
|
376
|
+
const h = hs[0]!;
|
|
377
|
+
const a = allowed(h, allow);
|
|
378
|
+
const where = [...new Set(hs.map((x) => x.screen))].map((sc) => `${sc} (${[...new Set(hs.filter((x) => x.screen === sc).map((x) => x.at))].join(", ")})`).join("; ");
|
|
379
|
+
const line = `- ${h.rule} · \`${h.path}\` · ${h.note} ${h.px > 0 ? "+" : ""}${h.px}px · ${where}`;
|
|
380
|
+
a ? ok.push(`${line} — allowed: ${a.reason}`) : lines.push(line);
|
|
381
|
+
}
|
|
382
|
+
const text = [`# UI alignment audit`, ``, `${screensRun} screen states measured; ${lines.length} flagged, ${ok.length} allowed${broken.length ? `, ${broken.length} could not be opened` : ""}.`, ``,
|
|
383
|
+
`## Flagged`, ``, ...(lines.length ? lines : ["None."]), ``, `## Allowed`, ``, ...(ok.length ? ok : ["None."]),
|
|
384
|
+
...allow.filter((a) => a.variant).map((a) => `- size · \`${a.variant}\` is its own size group — ${a.reason}`),
|
|
385
|
+
...(broken.length ? [``, `## Could not open`, ``, ...broken.map((b) => `- ${b}`)] : []), ``].join("\n");
|
|
386
|
+
return { text, flagged: lines.length };
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
if (import.meta.main) {
|
|
390
|
+
const out = resolve(arg("--out", join(tmpdir(), "ui-audit")));
|
|
391
|
+
const only = arg("--only").split(",").filter(Boolean);
|
|
392
|
+
const port = Number(arg("--port", "7459"));
|
|
393
|
+
const root = mkdtempSync(join(tmpdir(), "kz-ui-audit-"));
|
|
394
|
+
rmSync(out, { recursive: true, force: true });
|
|
395
|
+
mkdirSync(out, { recursive: true });
|
|
396
|
+
const allowFile = join(import.meta.dir, "ui-audit.allow.json");
|
|
397
|
+
const allow: Allow[] = existsSync(allowFile) ? JSON.parse(readFileSync(allowFile, "utf8")) : [];
|
|
398
|
+
let board: ReturnType<typeof Bun.spawn> | undefined, browser: Awaited<ReturnType<typeof startBrowser>> | undefined;
|
|
399
|
+
let code = 1;
|
|
400
|
+
try {
|
|
401
|
+
const project = scratchProject(root, sourceProject());
|
|
402
|
+
board = await startBoard(root, project, port);
|
|
403
|
+
browser = await startBrowser(root);
|
|
404
|
+
const base = `http://127.0.0.1:${port}`;
|
|
405
|
+
const st: any = await (await fetch(base + "/state")).json();
|
|
406
|
+
const runs = st.cards.filter((c: any) => c.kind === "run");
|
|
407
|
+
const run = (runs.find((c: any) => !["done", "abandoned"].includes(c.status)) ?? runs[0])?.id ?? "";
|
|
408
|
+
const empty = st.projects.flatMap((p: any) => p.workspaces.map((w: any) => ({ dir: p.dir, ws: w.path }))).find((w: any) => !runs.some((c: any) => c.state === w.dir)) ?? { dir: "", ws: "" };
|
|
409
|
+
const list = screens(join(project, ".kaizen"), run, empty).filter((s) => !only.length || only.some((o) => s.name === o || (o.endsWith("*") && s.name.startsWith(o.slice(0, -1)))));
|
|
410
|
+
const { hits, broken } = await audit(base, list, out, browser.page, allow, Bun.argv.includes("--shots"));
|
|
411
|
+
const n = list.reduce((a, s) => a + (s.widths ?? [1400, 400]).length * 2, 0);
|
|
412
|
+
const r = report(hits, broken, allow, n);
|
|
413
|
+
writeFileSync(join(out, "report.md"), r.text);
|
|
414
|
+
console.log(`\n${r.flagged} flagged, ${broken.length} could not be opened. Report: ${join(out, "report.md")}`);
|
|
415
|
+
code = r.flagged || broken.length ? 1 : 0;
|
|
416
|
+
} catch (e) {
|
|
417
|
+
console.error((e as Error).message);
|
|
418
|
+
} finally {
|
|
419
|
+
browser?.page.close();
|
|
420
|
+
browser?.proc.kill();
|
|
421
|
+
board?.kill();
|
|
422
|
+
await Promise.all([browser?.proc.exited, board?.exited]);
|
|
423
|
+
if (!Bun.argv.includes("--keep")) rmSync(root, { recursive: true, force: true });
|
|
424
|
+
else console.log(`Scratch kept: ${root}`);
|
|
425
|
+
}
|
|
426
|
+
process.exit(code);
|
|
427
|
+
}
|
package/cli/web.ts
CHANGED
|
@@ -41,6 +41,9 @@ import * as localsend from "./localsend.ts";
|
|
|
41
41
|
import * as hermes from "./hermes.ts";
|
|
42
42
|
import { listChats, readChat, sendChat, stopChat, deleteChat, okId as okChatId, busy as chatBusy, type Event as ChatEvent, type Upload as ChatUpload } from "./chat.ts";
|
|
43
43
|
import { workspaces, workspacesNow, forgetWorkspaces, workspacesAge, addWorktree, linkedWs, unlinkTerm, codeDir, runAsync, run, branchState, openPr, mergePr, removeWorktree } from "./worktree.ts";
|
|
44
|
+
import * as tasks from "./tasks.ts";
|
|
45
|
+
import * as taskService from "./task-service.ts";
|
|
46
|
+
import { artifactResponse as taskArtifactResponse } from "./task-results.ts";
|
|
44
47
|
import { gitUrl, destDir, winBad, cloneInto, branchesOf, ignoreKaizen } from "./add-project.ts";
|
|
45
48
|
|
|
46
49
|
const PAGE = join(dirname(import.meta.dir), "web", "board.html");
|
|
@@ -276,6 +279,23 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
276
279
|
: [cur]
|
|
277
280
|
).filter((d, i, arr) => arr.indexOf(d) === i && existsSync(d));
|
|
278
281
|
|
|
282
|
+
const taskHooks = {
|
|
283
|
+
launch: (dir: string, id: string, text: string, task: tasks.Task) => {
|
|
284
|
+
const live = liveAgent(dir, id);
|
|
285
|
+
if (live) { submitPty(live.key, text); return { ok: true, pty: live.key }; }
|
|
286
|
+
return launchRun({ severity: null, where: null, text, raw: text }, dir, id, { ...inCard(dir), task: { id: task.id, requirePlanConfirmation: !task.initialConfirmed } });
|
|
287
|
+
},
|
|
288
|
+
alive: (key: string) => ptyState(key)?.alive === true,
|
|
289
|
+
stop: (key: string) => killPty(key),
|
|
290
|
+
};
|
|
291
|
+
const taskPump = setInterval(() => {
|
|
292
|
+
for (const dir of states(true)) for (const task of tasks.listTasks(dir)) {
|
|
293
|
+
if (!task.safe || task.queuePaused || task.pendingDecision || !task.inputs.some(i => i.state === "queued")) continue;
|
|
294
|
+
try { taskService.dispatchReady(dir, task.id, taskHooks); changed(); } catch { /* CAS conflict: next pass reads the new state */ }
|
|
295
|
+
}
|
|
296
|
+
}, 1000);
|
|
297
|
+
taskPump.unref();
|
|
298
|
+
const taskProjects = () => states(true).filter(d => d !== join(home, ".kaizen")).map(dir => ({ dir, name: label(dir) }));
|
|
279
299
|
// Hostnames the user opted into (KAIZEN_WEB_HOSTS or ~/.kaizen/web-hosts, e.g. a
|
|
280
300
|
// `tailscale serve` name): matched exactly, empty when neither is set.
|
|
281
301
|
const extraHosts = { has: (h: string) => webHosts().has(h) };
|
|
@@ -1336,6 +1356,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1336
1356
|
if (body?.do === "login") return json(await loginUrl());
|
|
1337
1357
|
return bad("do: connect or login");
|
|
1338
1358
|
}
|
|
1359
|
+
// Settings → Mobile: WhatsApp bridge status and connect/disconnect.
|
|
1360
|
+
if (path === "/whatsapp") {
|
|
1361
|
+
if (!local(req)) return bad("cross-origin request refused", 403);
|
|
1362
|
+
const wa = await import("./whatsapp.ts");
|
|
1363
|
+
if (req.method === "GET") return json(await wa.whatsappStatus());
|
|
1364
|
+
if (req.method !== "POST") return bad("method not allowed", 405);
|
|
1365
|
+
const refused = strict(req);
|
|
1366
|
+
if (refused) return refused;
|
|
1367
|
+
let body: any;
|
|
1368
|
+
try { body = await req.json(); } catch { return bad("json body expected"); }
|
|
1369
|
+
if (body?.op === "connect") return json(await wa.whatsappConnect());
|
|
1370
|
+
if (body?.op === "disconnect") return json(await wa.whatsappDisconnect());
|
|
1371
|
+
return bad("op: connect or disconnect");
|
|
1372
|
+
}
|
|
1339
1373
|
if (req.method === "GET" && path === "/phone") {
|
|
1340
1374
|
// Async: a hung tailscale must not stall every terminal socket on this event loop.
|
|
1341
1375
|
let out = "";
|
|
@@ -1424,6 +1458,20 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
1424
1458
|
}), { headers: { "content-type": "application/manifest+json" } });
|
|
1425
1459
|
}
|
|
1426
1460
|
|
|
1461
|
+
if (req.method === "GET" && ["/tasks", "/task", "/task-artifact"].includes(path)) {
|
|
1462
|
+
const dir = qdir() ?? state ?? join(home, ".kaizen");
|
|
1463
|
+
if (!states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
1464
|
+
try {
|
|
1465
|
+
if (path === "/tasks") return json({ tasks: taskService.taskList(url.searchParams.get("all") === "1" ? states(true) : [dir], taskHooks), projects: taskProjects(), defaults: taskService.taskDefaults(dir) });
|
|
1466
|
+
const found = tasks.resolveTask(dir, url.searchParams.get("id") ?? url.searchParams.get("task") ?? "");
|
|
1467
|
+
if (!found || !states(true).includes(found.state)) return bad("unknown task", 404);
|
|
1468
|
+
if (path === "/task-artifact") return taskArtifactResponse(found.state, found.task.id, url.searchParams.get("result") ?? "", url.searchParams.get("artifact") ?? "", req, url.searchParams.get("download") === "1");
|
|
1469
|
+
let task = taskService.reconcile(found.state, found.task, taskHooks);
|
|
1470
|
+
if (task.safe && !task.queuePaused && !task.pendingDecision && task.inputs.some(i => i.state === "queued")) task = taskService.dispatchReady(found.state, task.id, taskHooks);
|
|
1471
|
+
return json({ task: taskService.taskView(found.state, task), results: taskService.resultViews(found.state, task.id), projects: taskProjects(), defaults: taskService.taskDefaults(found.state) });
|
|
1472
|
+
} catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
|
|
1473
|
+
}
|
|
1474
|
+
|
|
1427
1475
|
if (req.method === "GET" && path === "/state") {
|
|
1428
1476
|
const all = url.searchParams.get("all") === "1";
|
|
1429
1477
|
// Before the project list: it registers folders that turn out to be set up.
|
|
@@ -2150,7 +2198,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2150
2198
|
}
|
|
2151
2199
|
|
|
2152
2200
|
// No project here means the global inbox, which is where the TUI puts tasks too.
|
|
2153
|
-
let dir: string = body.dir ?? state ?? join(home, ".kaizen");
|
|
2201
|
+
let dir: string = path === "/task" && body.op === "create" && body.dir === null ? join(home, ".kaizen") : body.dir ?? state ?? join(home, ".kaizen");
|
|
2154
2202
|
// Choosing a folder from the projects folder is what sets it up: an empty
|
|
2155
2203
|
// .kaizen, which the first run fills in. Only folders the board offered.
|
|
2156
2204
|
if (path === "/cd" && dir === join(dirname(dir), ".kaizen") && (await fresh()).includes(dirname(dir))) {
|
|
@@ -2160,6 +2208,28 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2160
2208
|
}
|
|
2161
2209
|
if (!dir || !states(true).includes(dir)) return bad("unknown state dir", 404);
|
|
2162
2210
|
|
|
2211
|
+
if (path === "/task") {
|
|
2212
|
+
try {
|
|
2213
|
+
if (body.op === "project") {
|
|
2214
|
+
const found = tasks.resolveTask(dir, String(body.id ?? ""));
|
|
2215
|
+
if (!found || !states(true).includes(found.state)) return bad("unknown task", 404);
|
|
2216
|
+
if (found.task.revision !== Number(body.revision)) return bad("This task changed. Refresh before choosing a project.", 409);
|
|
2217
|
+
let destination = typeof body.projectDir === "string" ? canonState(body.projectDir) : "";
|
|
2218
|
+
if (body.name) { const made = await makeProject(String(body.name)); if ("error" in made) return bad(made.error, made.status ?? 400); if (!("dir" in made)) return bad("project not created"); destination = join(made.dir, ".kaizen"); }
|
|
2219
|
+
if (!destination || !states(true).includes(destination) || destination === join(home, ".kaizen")) return bad("Choose a named project", 400);
|
|
2220
|
+
const task = tasks.transferDraft(found.state, found.task.id, destination, dirname(destination));
|
|
2221
|
+
const result = taskService.taskAction(destination, { op: "start", id: task.id, revision: task.revision, operationId: String(body.operationId) + ":start" }, taskHooks);
|
|
2222
|
+
changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
|
|
2223
|
+
}
|
|
2224
|
+
if (!["create", "adopt"].includes(body.op)) {
|
|
2225
|
+
const found = tasks.resolveTask(dir, String(body.id ?? ""));
|
|
2226
|
+
if (!found || !states(true).includes(found.state)) return bad("unknown task", 404);
|
|
2227
|
+
}
|
|
2228
|
+
const result = taskService.taskAction(dir, body, taskHooks);
|
|
2229
|
+
changed(); return json({ ok: true, task: taskService.taskView(result.state, result.task) });
|
|
2230
|
+
} catch (e) { return bad((e as Error).message, e instanceof tasks.TaskError ? e.status : 400); }
|
|
2231
|
+
}
|
|
2232
|
+
|
|
2163
2233
|
// Only checks the project: the page that picked it sends it back in x-kz-dir.
|
|
2164
2234
|
if (path === "/cd") {
|
|
2165
2235
|
changed();
|
|
@@ -2599,6 +2669,7 @@ export async function web(repoDir: string, opts: Opts = {}) {
|
|
|
2599
2669
|
changed();
|
|
2600
2670
|
return json({ ok: true });
|
|
2601
2671
|
}
|
|
2672
|
+
if (run.task_id && run.awaiting === "approvals.plan") return bad("Confirm the current proposal on the task page so its version is checked.", 409);
|
|
2602
2673
|
if (!canApproveAwaiting(run.awaiting) || run.awaiting !== body.awaiting) return bad("this run is not waiting on that approval", 409);
|
|
2603
2674
|
if (run.awaiting === "findings" && body.why !== undefined) return bad("open findings can only be approved as-is or fixed individually", 409);
|
|
2604
2675
|
if (body.why !== undefined && !String(body.why).trim()) return bad("a revise needs a comment");
|