kaizen-agent 1.56.1 → 1.58.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.
@@ -7,10 +7,12 @@ 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 { ideaCombo, list, newDir, plogo, short, showList, showable } from "./projects.ts";
10
+ import { ideaCombo, list, newDir, plogo, setNewDir, short, showList, showable } from "./projects.ts";
11
11
  import { askNotify, toast } from "./toast.ts";
12
12
  import { answer, decided, resumable, resume } from "./approvals.ts";
13
13
  import { termsBadge } from "./terms.ts";
14
+ import { boardBadge, waitingCount } from "./badge.ts";
15
+ import { openWorkspace } from "./run-view.ts";
14
16
 
15
17
  let filter = null;
16
18
  let query = ""; // the header filter box, matched against a card's title and request
@@ -311,13 +313,40 @@ function inlineForm(c) {
311
313
  li.className = "inl";
312
314
  const dir = c.state;
313
315
  if (store.mode === "edit") {
314
- li.innerHTML = html`<input value="${c.text}"><textarea placeholder="Anything the planner should know">${c.notes || ""}</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">Save</button></div>`;
316
+ if (editFiles.k !== key(c)) editFiles = { k: key(c), files: [] };
317
+ const files = editFiles.files;
318
+ li.innerHTML = html`<input value="${c.text}"><textarea placeholder="Anything the planner should know">${c.notes || ""}</textarea><div class="row"><div class="att" id="editatt"></div><button type="button" class="ib" id="editpick" aria-label="Attach files" title="Attach files">${ico("clip")}</button></div><input type="file" id="editfile" multiple hidden><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">Save</button></div>`;
319
+ const shown = () => (li.querySelector("#editatt").textContent = files.map((f) => f.name).join(" · "));
320
+ const add = (f) => { files.push(f); shown(); };
321
+ shown();
322
+ li.querySelector("#editpick").onclick = () => li.querySelector("#editfile").click();
323
+ li.querySelector("#editfile").onchange = (e) => {
324
+ [...e.target.files].forEach(add);
325
+ e.target.value = "";
326
+ };
327
+ for (const el of [li.querySelector("input"), li.querySelector("textarea")])
328
+ el.onpaste = (e) => {
329
+ for (const it of e.clipboardData.items)
330
+ if (it.kind === "file") {
331
+ const f = it.getAsFile();
332
+ add(new File([f], f.name === "image.png" ? `paste-${Date.now()}.png` : f.name, { type: f.type }));
333
+ e.preventDefault();
334
+ }
335
+ };
315
336
  li.querySelector("[data-a=s]").onclick = async () => {
316
337
  const next = li.querySelector("input").value.trim(),
317
338
  notes = li.querySelector("textarea").value.trim();
339
+ if (!next) return;
340
+ if (next !== c.text || notes !== (c.notes || "")) {
341
+ const r = await post("/inbox", { op: "edit", dir, text: c.text, next, notes });
342
+ if (!r.ok) return;
343
+ }
344
+ if (files.length) {
345
+ const r = await post("/note", { dir, for: next, text: "", files: await dataUrls(files) });
346
+ if (!r.ok) toast("Idea saved, files not attached");
347
+ }
348
+ editFiles = { k: "", files: [] };
318
349
  store.mode = null;
319
- if (next && (next !== c.text || notes !== (c.notes || "")))
320
- await post("/inbox", { op: "edit", dir, text: c.text, next, notes });
321
350
  load();
322
351
  };
323
352
  }
@@ -364,19 +393,20 @@ function inlineForm(c) {
364
393
  };
365
394
  }
366
395
  if (store.mode === "run") {
367
- li.innerHTML = html`<div class="q">Run "${c.text}"</div><div class="q dim">Opens your agent with this request in a terminal.</div><div class="q dim">Full plans, builds, and checks with a separate reviewer. Lite does it in one session.</div><div id="run-pick" style="display:grid;gap:6px"><div id="run-agent" class="agents" role="radiogroup" aria-label="Agent"></div></div><div class="run-actions"><label class="yolo" id="run-yolo" title="Yolo: the agent runs every command and edit without asking" hidden><button type="button" class="chk" role="switch" aria-checked="false"></button>Yolo</label><div class="row"><button class="btn ghost" data-a="c">Cancel</button><button class="btn" data-a="l">Lite</button><button class="btn pri" data-a="s">Full run</button></div></div>`;
396
+ li.innerHTML = runHtml(c);
368
397
  li.querySelector("[data-a=s]").onclick = () => startRun(c, "full");
369
398
  li.querySelector("[data-a=l]").onclick = () => startRun(c, "lite");
370
399
  runForm(li, c);
371
400
  }
372
401
  li.querySelector("[data-a=c]").onclick = () => {
402
+ if (store.mode === "edit") editFiles = { k: "", files: [] };
373
403
  store.mode = null;
374
404
  render();
375
405
  };
376
406
  // Edit and reject take dictation; the run prompt has no field.
377
- li.querySelectorAll("input,textarea").forEach((f, i) => draft(f, "f:" + store.mode + ":" + store.modeKey + ":" + i));
407
+ li.querySelectorAll("input:not([type=file]),textarea").forEach((f, i) => draft(f, "f:" + store.mode + ":" + store.modeKey + ":" + i));
378
408
  if (store.mode !== "run") {
379
- const m = mic([...li.querySelectorAll("input,textarea")]);
409
+ const m = mic([...li.querySelectorAll("input:not([type=file]),textarea")]);
380
410
  if (m) li.querySelector(".row").prepend(m);
381
411
  }
382
412
  const inp = li.querySelector("input");
@@ -393,6 +423,24 @@ function inlineForm(c) {
393
423
  return li;
394
424
  }
395
425
 
426
+ const runHtml = (c) =>
427
+ html`<div class="q">Run "${c.text}"</div><div class="q dim">Opens your agent with this request in a terminal.</div><div class="q dim">Full plans, builds, and checks with a separate reviewer. Lite does it in one session.</div><div id="run-pick" style="display:grid;gap:6px"><div id="run-agent" class="agents" role="radiogroup" aria-label="Agent"></div></div><div class="run-actions"><label class="yolo" id="run-yolo" title="Yolo: the agent runs every command and edit without asking" hidden><button type="button" class="chk" role="switch" aria-checked="false"></button>Yolo</label><div class="row"><button type="button" class="btn ghost" data-a="c">Cancel</button><button type="button" class="btn" data-a="l">Lite</button><button type="button" class="btn pri" data-a="s">Full run</button></div></div>`;
428
+ // The run form as a popup over any page: Start in the new-idea form and on Ideas.
429
+ export function runPopup(c) {
430
+ const dl = modal(runHtml(c)),
431
+ f = dl.querySelector("form");
432
+ const go = (kind) => {
433
+ // startRun reads the Yolo switch, so the dialog closes after it has.
434
+ void startRun(c, kind);
435
+ dl.close();
436
+ };
437
+ f.querySelector<HTMLElement>("[data-a=s]").onclick = () => go("full");
438
+ f.querySelector<HTMLElement>("[data-a=l]").onclick = () => go("lite");
439
+ f.querySelector<HTMLElement>("[data-a=c]").onclick = () => dl.close();
440
+ runForm(f, c);
441
+ }
442
+
443
+ let editFiles = { k: "", files: [] };
396
444
  // The agent and Basic/Yolo picked in the open Run form. Kept here, not in the form:
397
445
  // the board is rebuilt on every server change, and the choice must outlive that.
398
446
  // Yolo never outlives the form: render() drops it once the form is closed.
@@ -462,6 +510,8 @@ async function startRun(c, kind) {
462
510
  toast((kind === "full" ? "Full" : kind === "lite" ? "Lite" : "Started") + (yolo ? " yolo" : "") + " run " + where(r) + ": " + via(r.agent));
463
511
  // A backlog card has no terminal of its own; the run's card gets it once the run exists.
464
512
  if (r.pty && !backlog) store.wantTerm = key(c);
513
+ // An idea's run opens in its workspace; the view follows it once the run card exists.
514
+ if (!backlog) openWorkspace(c);
465
515
  }
466
516
  load();
467
517
  }
@@ -472,12 +522,16 @@ const HINT = { 0: "Add an idea to start a run", 1: "Ideas you run are planned he
472
522
  // redraws the inline form on every change and a redraw would drop them.
473
523
  let newFiles = [];
474
524
  // The new-idea form, wired into f: inline at the top of Ideas, or in a modal.
525
+ // Opened from another page (Ideas, a workspace, the side menu): always the project picker,
526
+ // preset to that page's project or empty so one is chosen. The Board keeps its own rule.
527
+ let formPick: { dir: string | null } | null = null;
475
528
  function ideaForm(f, shut) {
529
+ const picking = store.all || !!formPick;
476
530
  const close = () => {
477
531
  newFiles = [];
478
532
  shut();
479
533
  };
480
- f.innerHTML = html`${store.all ? html`<div class="combo" id="ndc"><button type="button" class="sel" id="newdir" aria-label="Project for this idea" aria-haspopup="listbox" aria-expanded="false"></button><div class="menu-pop" hidden><input class="sel" aria-label="Search projects" placeholder="Search projects…" spellcheck="false" autocomplete="off"><div id="nds" role="listbox"></div></div></div>` : ""}<input id="newidea" placeholder="What do you want to build?"><textarea id="newnotes" placeholder="Anything the planner should know (optional)"></textarea><div class="att" id="newatt"></div><input type="file" id="newfile" multiple hidden><div class="row"><button type="button" class="ib" id="newpick" aria-label="Attach files" title="Attach files">${ico("clip")}</button><button type="button" class="btn ghost" id="nc">Cancel</button><div class="split"><button type="button" class="btn pri" id="ns">Add</button><button type="button" class="btn pri" id="nm" aria-label="More ways to add" aria-haspopup="menu" aria-expanded="false">${ico("chev")}</button><div class="menu-pop" role="menu" hidden><button type="button" role="menuitem" id="nr" title="Add the idea and run it now">${ico("play")}Start run</button></div></div></div>`;
534
+ f.innerHTML = html`${picking ? html`<div class="combo" id="ndc"><button type="button" class="sel" id="newdir" aria-label="Project for this idea" aria-haspopup="listbox" aria-expanded="false"></button><div class="menu-pop" hidden><input class="sel" aria-label="Search projects" placeholder="Search projects…" spellcheck="false" autocomplete="off"><div id="nds" role="listbox"></div></div></div>` : ""}<input id="newidea" placeholder="What do you want to build?"><label for="newnotes">Anything the planner should know <span class="dim">(optional)</span></label><textarea id="newnotes" placeholder="Context, constraints, examples, and what a good result looks like"></textarea><div class="att" id="newatt"></div><input type="file" id="newfile" multiple hidden><div class="row"><button type="button" class="ib" id="newpick" aria-label="Attach files" title="Attach files">${ico("clip")}</button><button type="button" class="btn ghost" id="nc">Cancel</button><div class="split"><button type="button" class="btn pri" id="ns">Add</button><button type="button" class="btn pri" id="nm" aria-label="More ways to add" aria-haspopup="menu" aria-expanded="false">${ico("chev")}</button><div class="menu-pop" role="menu" hidden><button type="button" role="menuitem" id="nr" title="Add the idea and run it now">${ico("play")}Start run</button></div></div></div>`;
481
535
  const inp = f.querySelector("#newidea"),
482
536
  files = newFiles;
483
537
  draft(inp, "f:new:0");
@@ -487,8 +541,13 @@ function ideaForm(f, shut) {
487
541
  const text = inp.value.trim();
488
542
  if (!text) return;
489
543
  const notes = f.querySelector("textarea").value.trim();
544
+ const dir = picking ? newDir : null;
545
+ if (picking && !dir) {
546
+ toast("Choose a project for this idea");
547
+ f.querySelector<HTMLElement>("#newdir")?.click();
548
+ return;
549
+ }
490
550
  close();
491
- const dir = store.all ? newDir : null;
492
551
  const r = await post("/inbox", dir ? { op: "add", dir, text, notes } : { op: "add", text, notes });
493
552
  if (r.ok) {
494
553
  toast("Idea added");
@@ -501,7 +560,7 @@ function ideaForm(f, shut) {
501
560
  if (run) {
502
561
  await load();
503
562
  const c = store.S.cards.find((x) => x.kind === "idea" && x.text === text && (!dir || x.state === dir));
504
- if (c) return startRun(c);
563
+ if (c) return runPopup(c);
505
564
  }
506
565
  }
507
566
  load();
@@ -526,7 +585,11 @@ function ideaForm(f, shut) {
526
585
  e.preventDefault();
527
586
  }
528
587
  };
529
- if (store.all) ideaCombo(f);
588
+ if (picking) {
589
+ if (formPick) setNewDir(formPick.dir);
590
+ // From another page a choice is always required: a preset project the picker does not offer is not swapped for another.
591
+ ideaCombo(f, !!formPick);
592
+ }
530
593
  f.querySelector("#ns").onclick = () => save(false);
531
594
  f.querySelector("#nr").onclick = () => save(true);
532
595
  {
@@ -577,7 +640,9 @@ function ideaForm(f, shut) {
577
640
  }
578
641
 
579
642
  // New idea from the top bar, the empty board or n: the same form, in a modal.
580
- export function newIdea() {
643
+ export function newIdea(from?: { dir: string | null }) {
644
+ // The header button passes its click event: only an explicit { dir } is another page's call.
645
+ formPick = from && "dir" in from ? from : null;
581
646
  if (store.mode === "new") {
582
647
  store.mode = null;
583
648
  render();
@@ -596,6 +661,7 @@ export function render() {
596
661
  if (store.mode && store.mode !== "new" && ![...store.S.cards, ...backlogList()].some((c) => key(c) === store.modeKey))
597
662
  store.mode = null;
598
663
  if (store.mode !== "run" && runPick) runPick.yolo = false;
664
+ if (store.mode !== "edit") editFiles = { k: "", files: [] };
599
665
  if (!store.mode) undraft("f:");
600
666
  // Reassigned, not emptied: a form still open (the modal) keeps its own array.
601
667
  if (store.mode !== "new") newFiles = [];
@@ -878,8 +944,9 @@ export function render() {
878
944
  b.appendChild(s);
879
945
  });
880
946
  // The tab says how many runs wait on you, or agents wait on input, so a background tab still tells you.
881
- const nw = store.S.cards.filter((c) => !c.archived && ((c.kind === "run" && c.status === "waiting") || (c.pty?.alive && c.pty.asking))).length;
947
+ const nw = waitingCount(store.S.cards);
882
948
  document.title = nw ? `(${nw}) kaizen` : "kaizen";
949
+ if (store.all) boardBadge(store.S.cards, store.S.projects);
883
950
  termsBadge();
884
951
  stopDictation(false); // forms were just rebuilt; a listener whose field is gone would write into nothing
885
952
  if (fk && document.activeElement === document.body) cardEl(fk)?.focus({ preventScroll: true });
@@ -0,0 +1,247 @@
1
+ import { store } from "./store.ts";
2
+ import { dirHeader } from "./api.ts";
3
+ import { open } from "./panel.ts";
4
+ import { key } from "./cards.ts";
5
+ import { go } from "./views.ts";
6
+
7
+ const box = () => document.getElementById("context")!;
8
+ const body = () => document.getElementById("context-body")!;
9
+ let tab = "files";
10
+ let folder = "";
11
+ let generation = 0;
12
+ let closeMobile = () => {};
13
+
14
+ const button = (label: string, action: () => void, cls = "tree-row") => {
15
+ const el = document.createElement("button");
16
+ el.className = cls;
17
+ el.textContent = label;
18
+ el.onclick = action;
19
+ return el;
20
+ };
21
+ const message = (text: string) => {
22
+ body().textContent = text;
23
+ };
24
+ const request = async (route: string) => {
25
+ const response = await fetch(route, { headers: dirHeader() });
26
+ const data = await response.json();
27
+ if (!response.ok) throw new Error(data.error || data.message || "Could not load this project");
28
+ return data;
29
+ };
30
+ const selectedDir = () => store.dir || store.S.dir;
31
+
32
+ async function notes() {
33
+ const gen = ++generation;
34
+ message("Loading notes…");
35
+ try {
36
+ const data = await request("/vault?dir=" + encodeURIComponent(selectedDir() || ""));
37
+ if (gen !== generation) return;
38
+ body().replaceChildren();
39
+ const list = data.notes.sort((a, b) => a.name.localeCompare(b.name));
40
+ if (!list.length) return message("No notes in this project yet.");
41
+ for (const note of list) {
42
+ const link = document.createElement("a");
43
+ link.className = "tree-row";
44
+ link.style.paddingLeft = 8 + 10 * Math.min(note.name.split("/").length - 1, 4) + "px";
45
+ link.textContent = note.name;
46
+ link.href = "/notebook?dir=" + encodeURIComponent(data.dir) + "&note=" + encodeURIComponent(note.name);
47
+ body().append(link);
48
+ }
49
+ } catch (error) {
50
+ if (gen === generation) message(String(error));
51
+ }
52
+ }
53
+
54
+ async function files(path = folder) {
55
+ folder = path;
56
+ const gen = ++generation;
57
+ message("Loading files…");
58
+ try {
59
+ const data = await request(
60
+ "/project-tree?dir=" + encodeURIComponent(selectedDir() || "") + "&path=" + encodeURIComponent(path),
61
+ );
62
+ if (gen !== generation) return;
63
+ body().replaceChildren();
64
+ if (path)
65
+ body().append(button("← " + path, () => files(path.split("/").slice(0, -1).join("/")), "tree-row tree-back"));
66
+ if (!data.entries.length) body().append("This folder is empty.");
67
+ for (const entry of data.entries) {
68
+ const next = path ? path + "/" + entry.name : entry.name;
69
+ body().append(
70
+ button(
71
+ (entry.dir ? "▸ " : " ") + entry.name,
72
+ () => (entry.dir ? files(next) : file(next)),
73
+ "tree-row" + (entry.dir ? " folder" : ""),
74
+ ),
75
+ );
76
+ }
77
+ } catch (error) {
78
+ if (gen === generation) message(String(error));
79
+ }
80
+ }
81
+
82
+ async function file(path: string) {
83
+ const gen = ++generation;
84
+ message("Loading file…");
85
+ try {
86
+ const data = await request(
87
+ "/project-text?dir=" + encodeURIComponent(selectedDir() || "") + "&path=" + encodeURIComponent(path),
88
+ );
89
+ if (gen !== generation) return;
90
+ body().replaceChildren();
91
+ const actions = document.createElement("div");
92
+ actions.className = "ctx-actions";
93
+ actions.append(button("← Files", () => files(folder), "btn"));
94
+ const download = document.createElement("a");
95
+ download.className = "btn";
96
+ download.textContent = "Download";
97
+ download.href =
98
+ "/project-text?dir=" +
99
+ encodeURIComponent(selectedDir() || "") +
100
+ "&path=" +
101
+ encodeURIComponent(path) +
102
+ "&download=1";
103
+ actions.append(download);
104
+ const title = document.createElement("strong");
105
+ title.textContent = path;
106
+ const pre = document.createElement("pre");
107
+ pre.textContent = data.content;
108
+ body().append(actions, title, pre);
109
+ } catch (error) {
110
+ if (gen === generation) message(String(error));
111
+ }
112
+ }
113
+
114
+ function terminals() {
115
+ ++generation;
116
+ body().replaceChildren();
117
+ body().append(
118
+ button(
119
+ "Open terminal workspace",
120
+ () => {
121
+ if (!matchMedia("(min-width:1201px)").matches) closeMobile();
122
+ tab = "files";
123
+ render();
124
+ go("terminal", true);
125
+ },
126
+ "btn",
127
+ ),
128
+ );
129
+ const sessions = store.S.cards.filter((c) => c.pty && !c.archived);
130
+ if (!sessions.length) {
131
+ const empty = document.createElement("p");
132
+ empty.textContent = "No terminal sessions yet.";
133
+ body().append(empty);
134
+ return;
135
+ }
136
+ for (const card of sessions)
137
+ body().append(
138
+ button((card.pty.alive ? "● " : "○ ") + (card.id || String(card.text).split("\n")[0]), () => {
139
+ store.wantTerm = key(card);
140
+ if (!matchMedia("(min-width:1201px)").matches) closeMobile();
141
+ open(card);
142
+ }),
143
+ );
144
+ }
145
+
146
+ function render() {
147
+ const dir = selectedDir();
148
+ document.getElementById("context-title")!.textContent = dir
149
+ ? dir.split(/[\\/]/).filter(Boolean).at(-2) || "Project"
150
+ : "Project";
151
+ box()
152
+ .querySelectorAll<HTMLButtonElement>("[data-context]")
153
+ .forEach((el) => {
154
+ el.classList.toggle("on", el.dataset.context === tab);
155
+ el.setAttribute("aria-pressed", String(el.dataset.context === tab));
156
+ });
157
+ if (tab === "notes") void notes();
158
+ else if (tab === "files") void files();
159
+ else terminals();
160
+ }
161
+
162
+ export function initContext() {
163
+ const wide = matchMedia("(min-width:1201px)");
164
+ const opener = document.getElementById("ctx-open")!;
165
+ const setOpen = (value: boolean) => {
166
+ const modal = value && !wide.matches;
167
+ box().classList.toggle("on", value);
168
+ opener.setAttribute("aria-expanded", String(value));
169
+ box().setAttribute("role", wide.matches ? "complementary" : "dialog");
170
+ if (modal) box().setAttribute("aria-modal", "true");
171
+ else box().removeAttribute("aria-modal");
172
+ document.querySelector<HTMLElement>(".rail")!.inert = modal;
173
+ for (const child of document.querySelector<HTMLElement>(".app")!.children)
174
+ if (child !== box()) (child as HTMLElement).inert = modal;
175
+ };
176
+ closeMobile = () => setOpen(false);
177
+ const sync = () => {
178
+ setOpen(wide.matches);
179
+ };
180
+ wide.addEventListener("change", () => {
181
+ sync();
182
+ if (wide.matches) render();
183
+ });
184
+ sync();
185
+ opener.onclick = () => {
186
+ const next = !box().classList.contains("on");
187
+ setOpen(next);
188
+ if (next) {
189
+ render();
190
+ if (!wide.matches) box().querySelector<HTMLElement>("[data-context].on")?.focus();
191
+ }
192
+ };
193
+ document.getElementById("ctx-close")!.onclick = () => {
194
+ setOpen(false);
195
+ opener.focus();
196
+ };
197
+ addEventListener(
198
+ "keydown",
199
+ (event) => {
200
+ if (wide.matches || !box().classList.contains("on")) return;
201
+ if (event.key === "Escape") {
202
+ event.preventDefault();
203
+ event.stopPropagation();
204
+ setOpen(false);
205
+ opener.focus();
206
+ } else if (event.key === "Tab") {
207
+ const items = [...box().querySelectorAll<HTMLElement>("button,a[href]")].filter(
208
+ (item) => !item.hasAttribute("disabled") && item.getClientRects().length,
209
+ );
210
+ const first = items[0],
211
+ last = items.at(-1);
212
+ if (!first || !last) return;
213
+ if (
214
+ !box().contains(document.activeElement) ||
215
+ (event.shiftKey && document.activeElement === first) ||
216
+ (!event.shiftKey && document.activeElement === last)
217
+ ) {
218
+ event.preventDefault();
219
+ (event.shiftKey ? last : first).focus();
220
+ }
221
+ }
222
+ },
223
+ true,
224
+ );
225
+ addEventListener("kz-view", () => {
226
+ if (!wide.matches) setOpen(false);
227
+ });
228
+ box()
229
+ .querySelectorAll<HTMLButtonElement>("[data-context]")
230
+ .forEach(
231
+ (el) =>
232
+ (el.onclick = () => {
233
+ tab = el.dataset.context!;
234
+ render();
235
+ }),
236
+ );
237
+ let lastDir = selectedDir();
238
+ addEventListener("kz-state", () => {
239
+ const now = selectedDir();
240
+ if (now !== lastDir) {
241
+ lastDir = now;
242
+ folder = "";
243
+ if (box().classList.contains("on")) render();
244
+ } else if (box().classList.contains("on") && tab === "terminal") terminals();
245
+ });
246
+ render();
247
+ }
package/web/board/home.ts CHANGED
@@ -33,8 +33,7 @@ const sideAtStart = () => {
33
33
  function setSide(on) {
34
34
  side = on;
35
35
  $("home").classList.toggle("hopen", on);
36
- const t = $("htog");
37
- if (t) t.setAttribute("aria-expanded", String(on)), (t.title = on ? "Hide chats" : "Show chats");
36
+ for (const t of [$("htog"), $("hsidetop")]) if (t) t.setAttribute("aria-expanded", String(on)), (t.title = on ? "Hide chats" : "Show chats");
38
37
  if (!phone())
39
38
  try {
40
39
  localStorage.setItem("kz-hist", on ? "1" : "0");
@@ -180,10 +179,11 @@ function draw() {
180
179
  if (shown !== (cur && cur.id)) seen = 0;
181
180
  if (side === null) side = sideAtStart();
182
181
  h.classList.toggle("hopen", side);
183
- h.innerHTML = String(html`<div class="hside">${list()}</div><div class="hscrim" id="hscrim"></div><div class="hmain${empty ? " hfresh" : ""}"><div class="htop"><button class="ib" id="htog" aria-label="Chats" aria-expanded="${String(side)}" title="${side ? "Hide chats" : "Show chats"}">${ico("side")}</button></div><div class="hlog" id="hlog" aria-live="polite">${empty ? hero() : cur.messages.map(msg)}</div><form class="hbox" id="hbox"><input id="hfile" type="file" multiple hidden><button type="button" class="ib hattach" id="hattach" aria-label="Attach files" title="Attach files">${ico("clip")}</button><div class="hinput"><div class="hatt" id="hatt"></div><textarea id="hq" rows="1" placeholder="Ask anything, or describe what to build…" aria-label="Message the agent"></textarea></div>${empty ? "" : html`<span class="hwhere" title="Project">${ico("board")}${cur.project ? name(cur.project) : "No project"}</span>`}${sendButton()}</form>${empty ? chips() : ""}</div>`);
182
+ h.innerHTML = String(html`<div class="hside">${list()}</div><div class="hscrim" id="hscrim"></div><div class="hmain${empty ? " hfresh" : ""}"><div class="htop"><button class="ib" id="htog" aria-label="Chats" aria-expanded="${String(side)}" title="${side ? "Hide chats" : "Show chats"}">${ico("side")}</button></div><div class="hlog" id="hlog" aria-live="polite">${empty ? hero() : cur.messages.map(msg)}</div><form class="hbox" id="hbox"><input id="hfile" type="file" multiple hidden><button type="button" class="ib hattach" id="hattach" aria-label="Attach files" title="Attach files">${ico("clip")}</button><div class="hinput"><div class="hatt" id="hatt"></div><textarea id="hq" rows="1" placeholder="${phone() ? "Ask or describe what to build…" : "Ask anything, or describe what to build…"}" aria-label="Message the agent"></textarea></div>${empty ? "" : html`<span class="hwhere" title="Project">${ico("board")}${cur.project ? name(cur.project) : "No project"}</span>`}${sendButton()}</form>${empty ? chips() : ""}</div>`);
184
183
  seen = empty ? 0 : cur.messages.length;
185
184
  shown = cur && cur.id;
186
185
  $("htog").onclick = () => setSide(!side);
186
+ $("hsidetop").onclick = () => setSide(!side);
187
187
  $("hscrim").onclick = () => setSide(false);
188
188
  const q = $("hq");
189
189
  renderAttachments();
@@ -0,0 +1,173 @@
1
+ // The Ideas page (?view=ideas): every idea and run across projects as one table, with
2
+ // source, project, Open/Running/Done and text filters. A card's source is the icebox
3
+ // signal it came from (its `idea` text or `run` id); one typed by hand is "Manual".
4
+ // The data is the rail's (workspace.ts): no fetch of its own.
5
+ import { store } from "./store.ts";
6
+ import { $, html, ico, raw } from "./dom.ts";
7
+ import { age, NAMES } from "./labels.ts";
8
+ import { key, runPopup } from "./cards.ts";
9
+ import { openWorkspace } from "./run-view.ts";
10
+ import { refreshBoardBadge } from "./badge.ts";
11
+ import { cardHref, drawSources, logo, railData, srcIcon, stateOf, titleOf } from "./workspace.ts";
12
+
13
+ const WORDS = { idle: "Idea", plan: "Planning", build: "Building", review: "Reviewing", wait: "Waiting on you", done: "Done", aband: "Abandoned", stalled: "Stalled" };
14
+ const PLAT = { x: "X", tiktok: "TikTok", instagram: "Instagram", threads: "Threads" };
15
+ const AGENTS = ["claude", "codex", "agy", "opencode", "gemini", "cursor"];
16
+ // sort: on Open, ideas first or running first (kept per browser).
17
+ const f = { src: "all", proj: "", show: "open", q: "", sort: (() => { try { return localStorage.getItem("kz-ideas-sort") || "runs"; } catch { return "runs"; } })() };
18
+ let go: (v: string, push?: boolean) => void = () => {};
19
+
20
+ const nameOf = (dir, projects) => {
21
+ const l = projects?.find((p) => p.dir === dir)?.label || dir.replace(/[\\/]\.kaizen$/, "");
22
+ return l.split(/[\\/]/).pop() || l;
23
+ };
24
+ const srcLabel = (s) => s.label || PLAT[s.social] || (() => { try { return new URL(s.url).hostname.replace(/^www\./, ""); } catch { return s.url; } })();
25
+
26
+ // Each card's source url, or "" for a hand-typed one.
27
+ function sourcesOf(cards, d) {
28
+ const sigs = [...(d?.icebox ?? []), ...(d?.dismissed ?? [])];
29
+ const of = new Map<any, string>();
30
+ for (const c of cards) {
31
+ const s = sigs.find((s) => s.dir === c.state && ((c.kind === "run" && s.run === c.id) || (s.idea && (s.idea === c.text || s.idea === c.title))));
32
+ // A hand-added icebox item ("manual") is no outside source either.
33
+ of.set(c, /^https?:\/\//.test(s?.source ?? "") ? s.source : "");
34
+ }
35
+ return of;
36
+ }
37
+
38
+ // Keyboard: the row picked with the arrow keys (from the search box or the page), Enter acts on it.
39
+ let sel = 0;
40
+ let shownRows: any[] = [];
41
+ function draw() {
42
+ const box = $("ideasv");
43
+ if (!document.body.classList.contains("ideav")) return;
44
+ const { cards: all, projects, srcs } = railData();
45
+ const cards = all.filter((c) => !c.archived);
46
+ const src = sourcesOf(cards, srcs);
47
+ const known = new Map<string, any>((srcs?.sources ?? []).map((s) => [s.url, s]));
48
+ const present = [...new Set(cards.map((c) => src.get(c)!))];
49
+ if (f.src !== "all" && !present.includes(f.src)) f.src = "all";
50
+ const dirs = [...new Set(cards.map((c) => c.state))];
51
+ // "Showing": the same projects-shown set as the Board and the Icebox (store.shown).
52
+ const shownDirs = dirs.filter((d) => store.shown.has(d));
53
+ // The Board's header is the Ideas header too (as on the Icebox): its project picker, its
54
+ // Showing list and its search box drive this table.
55
+ const proj = store.all ? "" : store.S?.dir ?? "";
56
+ const q = (($("bq") as HTMLInputElement | null)?.value ?? "").trim().toLowerCase();
57
+ const fin = (c) => c.status === "done" || c.status === "abandoned";
58
+ const rows = cards
59
+ .filter((c) => f.src === "all" || src.get(c) === f.src)
60
+ .filter((c) => (proj ? c.state === proj : !shownDirs.length || shownDirs.includes(c.state)))
61
+ // Open: ideas not started yet and runs in flight. Running: runs in flight only. Done: finished runs.
62
+ .filter((c) => (f.show === "done" ? fin(c) : f.show === "running" ? c.kind === "run" && !fin(c) : !fin(c)))
63
+ .filter((c) => !q || (titleOf(c) + " " + nameOf(c.state, projects)).toLowerCase().includes(q))
64
+ // On Open, ideas above runs or runs above ideas, as chosen; newest first within each.
65
+ .sort((a, b) => (f.show === "open" ? (a.kind === b.kind ? 0 : (a.kind === "idea") === (f.sort === "ideas") ? -1 : 1) : 0) || (b.moved ?? b.added ?? 0) - (a.moved ?? a.added ?? 0));
66
+ const now = Date.now();
67
+ const seg = (v, l) => html`<button class="pill${f.show === v ? " on" : ""}" data-show="${v}">${l}</button>`;
68
+ const srcName = (u) => (u === "all" ? "All sources" : u === "" ? "Manual" : known.get(u) ? srcLabel(known.get(u)) : srcLabel({ url: u }));
69
+ const srcMark = (u) => (u === "all" ? raw('<svg><use href="#r-bulb"/></svg>') : u === "" ? ico("pen") : srcIcon(known.get(u) ?? { url: u }));
70
+ const srcList = ["all", ...present.filter(Boolean), ...(present.includes("") ? [""] : [])];
71
+ // A pop-up picker: a button that opens a short list.
72
+ const pop = (id, label, rows) => html`<details class="combo ipop" id="${id}"><summary class="sel">${label}</summary><div class="menu-pop pick-list">${rows}</div></details>`;
73
+ const ck = raw('<svg class="ck"><use href="#i-check"/></svg>');
74
+ const sources = pop(
75
+ "ideas-src",
76
+ html`${srcMark(f.src)}<span>${srcName(f.src)}</span>`,
77
+ html`${srcList.map((u) => html`<button type="button" role="menuitemradio" data-src="${u}" aria-checked="${String(f.src === u)}">${srcMark(u)}<span>${srcName(u)}</span>${ck}</button>`)}`,
78
+ );
79
+ // Ideas' own filters, placed in the shared header after its search box.
80
+ const sortPop =
81
+ f.show === "open"
82
+ ? pop(
83
+ "ideas-sort",
84
+ html`<span>${f.sort === "ideas" ? "Ideas first" : "Running first"}</span>`,
85
+ html`${[["ideas", "Ideas first"], ["runs", "Running first"]].map(([v, l]) => html`<button type="button" role="menuitemradio" data-sort="${v}" aria-checked="${String(f.sort === v)}"><span>${l}</span>${ck}</button>`)}`,
86
+ )
87
+ : "";
88
+ const extra = html`<span class="iseg">${seg("open", "Open")}${seg("running", "Running")}${seg("done", "Done")}</span>${sortPop}${sources}<button class="ib" id="ideas-ref" title="Refresh" aria-label="Refresh">${ico("refresh")}</button>`;
89
+ const table = html`<table class="itable"><thead><tr><th></th><th>Title / context</th><th>Status</th><th>Updated</th><th></th></tr></thead><tbody>${rows.map((c, i) => {
90
+ const name = nameOf(c.state, projects),
91
+ st = stateOf(c),
92
+ agent = (c.tags ?? []).find((t) => AGENTS.includes(t));
93
+ return html`<tr><td>${logo(c.state, name, projects)}</td><td><b>${titleOf(c)}</b><div class="ctx">${name}${agent ? html`<span class="tag">${NAMES[agent]}</span>` : ""}</div></td><td><span class="stc"><span class="si ${st}"></span>${WORDS[st]}</span></td><td class="d">${c.moved || c.added ? age(c.moved || c.added, now) + " ago" : ""}</td><td><button class="go" data-i="${i}">${c.kind === "idea" ? "Start" : "Open"} ${ico("arrow")}</button></td></tr>`;
94
+ })}</tbody></table>${rows.length ? "" : html`<p class="none">Nothing matches.</p>`}`;
95
+ const hx = $("hx");
96
+ // Not while a pop-up in it is open: redrawing would close it under the pointer.
97
+ if (!hx.querySelector("details[open]")) hx.innerHTML = String(extra);
98
+ box.innerHTML = String(html`<div class="ibox"><div class="iscroll">${table}</div></div>`);
99
+
100
+ hx.querySelectorAll<HTMLElement>("[data-src]").forEach((b) => (b.onclick = () => ((f.src = b.dataset.src!), (hx.innerHTML = ""), draw())));
101
+ hx.querySelectorAll<HTMLElement>("[data-sort]").forEach(
102
+ (b) =>
103
+ (b.onclick = () => {
104
+ f.sort = b.dataset.sort!;
105
+ try {
106
+ localStorage.setItem("kz-ideas-sort", f.sort);
107
+ } catch {}
108
+ hx.innerHTML = "";
109
+ draw();
110
+ }),
111
+ );
112
+ hx.querySelectorAll<HTMLElement>("[data-show]").forEach((b) => (b.onclick = () => ((f.show = b.dataset.show!), (hx.innerHTML = ""), draw())));
113
+ $("ideas-ref").onclick = () => (void drawSources(true), void refreshBoardBadge());
114
+ box.querySelectorAll<HTMLElement>("button.go").forEach((b) => (b.onclick = () => act(rows[+b.dataset.i!])));
115
+ shownRows = rows;
116
+ sel = Math.max(0, Math.min(sel, rows.length - 1));
117
+ mark();
118
+ }
119
+
120
+ // Start: the run form in a popup (agent pick, then go), then the run workspace. Open: the card.
121
+ // Cards of a project this board is not showing go through the board's deep link.
122
+ function act(c) {
123
+ const here = store.S.cards.find((x) => key(x) === key(c));
124
+ if (!here) {
125
+ location.href = c.kind === "run" ? cardHref(c) + "&all=1" : `/?all=1&dir=${encodeURIComponent(c.state)}&idea=${encodeURIComponent(c.text)}`;
126
+ return;
127
+ }
128
+ if (c.kind === "run") return openWorkspace(here);
129
+ runPopup(here);
130
+ }
131
+
132
+ function mark() {
133
+ const trs = [...document.querySelectorAll<HTMLElement>("#ideasv tbody tr")];
134
+ trs.forEach((tr, i) => tr.classList.toggle("kb", i === sel));
135
+ trs[sel]?.scrollIntoView({ block: "nearest" });
136
+ }
137
+ addEventListener("keydown", (e) => {
138
+ if (!document.body.classList.contains("ideav") || !shownRows.length) return;
139
+ const t = e.target as HTMLElement;
140
+ // From the search box, or anywhere on the page that is not another field or a menu.
141
+ if (t.id !== "bq" && (t.closest("input,textarea,select,[contenteditable],details,dialog") || t.isContentEditable)) return;
142
+ if (e.key === "ArrowDown" || e.key === "ArrowUp") {
143
+ e.preventDefault();
144
+ sel = Math.max(0, Math.min(shownRows.length - 1, sel + (e.key === "ArrowDown" ? 1 : -1)));
145
+ mark();
146
+ } else if (e.key === "Enter" && !e.isComposing) {
147
+ e.preventDefault();
148
+ act(shownRows[sel]);
149
+ }
150
+ });
151
+ export function openIdeas() {
152
+ $("bq").placeholder = "Search ideas (press /)";
153
+ addEventListener("kz-view", () => ($("bq").placeholder = "Filter cards (press /)"), { once: true });
154
+ void drawSources(true);
155
+ draw();
156
+ }
157
+ export function initIdeas(goTo: typeof go) {
158
+ go = goTo;
159
+ addEventListener("kz-rail", draw);
160
+ // The shared header's search box, project picker and Showing list.
161
+ addEventListener("kz-state", draw);
162
+ $("bq")?.addEventListener("input", () => ((sel = 0), draw()));
163
+ $("shows")?.addEventListener("click", () => queueMicrotask(draw));
164
+ }
165
+
166
+ // A click outside the Ideas header's pop-ups closes them.
167
+ addEventListener(
168
+ "pointerdown",
169
+ (e) => {
170
+ if (!(e.target as Element).closest?.("details.ipop")) document.querySelectorAll<HTMLDetailsElement>("details.ipop[open]").forEach((d) => (d.open = false));
171
+ },
172
+ true,
173
+ );