kaizen-agent 1.84.0 → 1.85.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,7 +2,7 @@ import { post } from "./api.ts";
2
2
  import { $, html, raw, toggleSwitch } from "./dom.ts";
3
3
  import { toast } from "./toast.ts";
4
4
 
5
- // Settings → Workflows → Automations: schedules that start a run in this project. /automations
5
+ // Settings → Automations: schedules that start a run in this project. /automations
6
6
  // answers for the page's project; the server makes every decision, this only draws and posts.
7
7
  type Hist = { fire: string; at: number; kind: string; status: string; reason?: string; run?: string };
8
8
  type Rule = { id: string; name: string; text: string; cron: string; kind: string; enabled: boolean; agent?: string; precheck?: string; precheck_timeout: number; grace_minutes: number; next: number | null; history: Hist[] };
@@ -2,7 +2,7 @@ import { post } from "./api.ts";
2
2
  import { $, html } from "./dom.ts";
3
3
  import { toast } from "./toast.ts";
4
4
 
5
- // Settings → General → Cleanup: the two halves of `kaizen prune`, one button each, so
5
+ // Settings → General → Storage: the two halves of `kaizen prune`, one button each, so
6
6
  // clearing dead launch records never takes run history with it.
7
7
  export type Cleanup = { project: string | null; keep: number; records: { abandoned: number; unowned: number; gone: number }; runs: number; rescued: number };
8
8
 
@@ -1,50 +1,59 @@
1
- // Settings' sidebar, grouped as Orca's is. Only the page knows this: a setting's `group`
2
- // in cli/settings.ts still decides its scope and the TUI's headings.
1
+ // Settings' sidebar, grouped as macOS System Settings is: short groups of pages, each with
2
+ // its icon tile. Only the page knows this: a setting's `group` in cli/settings.ts still
3
+ // decides its scope and the TUI's headings.
3
4
  export type SettingsPage = { id: string; title: string; desc: string; ico: string };
4
5
  export const SETTINGS_NAV: [string, SettingsPage[]][] = [
5
- ["AI Capabilities", [
6
+ ["App", [
7
+ { id: "general", title: "General", desc: "About kaizen, storage, folders and how the app opens.", ico: "gear" },
8
+ { id: "appearance", title: "Appearance", desc: "Theme, color and motion in this browser.", ico: "sun" },
9
+ { id: "notifications", title: "Notifications", desc: "Notices and sounds in this browser.", ico: "inbox" },
10
+ { id: "keyboard", title: "Keyboard & Dictation", desc: "Shortcuts, and speech-to-text dictation run in the browser.", ico: "kbd" },
11
+ { id: "terminal", title: "Terminal", desc: "Board terminals and the terminal dashboard.", ico: "term" },
12
+ ]],
13
+ ["Agents", [
6
14
  { id: "agents", title: "Agents", desc: "Manage AI agents, set a default, and customize commands.", ico: "ai" },
7
- { id: "accounts", title: "AI Provider Accounts", desc: "Who is signed in to each AI tool kaizen runs. Add accounts only to switch between more than one.", ico: "link" },
8
- { id: "orchestration", title: "Orchestration", desc: "Split a run into workers, each in its own terminal. Off by default.", ico: "ai" },
15
+ { id: "models", title: "Models", desc: "The model each agent runs its stages and handoff sessions on.", ico: "mem" },
16
+ { id: "accounts", title: "AI Accounts", desc: "Who is signed in to each AI tool kaizen runs. Add accounts only to switch between more than one.", ico: "link" },
9
17
  { id: "skills", title: "Skills", desc: "What your agents can do. Changes apply to new sessions.", ico: "note" },
10
- { id: "voice", title: "Voice", desc: "Speech-to-text dictation, run in the browser.", ico: "mic" },
11
- ]],
12
- ["Set Up", [
13
- { id: "general", title: "General", desc: "Which settings you are editing, folders, and maintenance.", ico: "gear" },
14
- { id: "integrations", title: "Integrations", desc: "Request sources, your Google account, and web research.", ico: "link" },
15
- { id: "mobile", title: "Mobile", desc: "Open kaizen from your phone.", ico: "send" },
16
18
  ]],
17
- ["Workflows", [
19
+ ["Workflow", [
20
+ { id: "runs", title: "Runs", desc: "How a run is carried out: who builds, who reviews, and what it remembers.", ico: "play" },
18
21
  { id: "approvals", title: "Approvals", desc: "Where a run stops and waits for you.", ico: "check" },
19
22
  { id: "autofix", title: "Auto-fix", desc: "What happens to review findings.", ico: "bug" },
23
+ { id: "orchestration", title: "Orchestration", desc: "Split a run into workers, each in its own terminal. Off by default.", ico: "lgrid" },
20
24
  { id: "automations", title: "Automations", desc: "Schedules that start a run in this project.", ico: "clock" },
21
- { id: "git", title: "Git & Source Control", desc: "Branches and commits for each run.", ico: "pen" },
22
- { id: "terminal", title: "Terminal", desc: "The terminal dashboard.", ico: "term" },
25
+ { id: "git", title: "Git", desc: "Branches and commits for each run.", ico: "pen" },
23
26
  ]],
24
- ["Interface", [
25
- { id: "appearance", title: "Appearance", desc: "Theme, color and motion in this browser.", ico: "note" },
26
- { id: "notifications", title: "Notifications", desc: "Notices and sounds in this browser.", ico: "clock" },
27
- { id: "shortcuts", title: "Shortcuts", desc: "Keyboard shortcuts for common actions.", ico: "kbd" },
27
+ ["Connections", [
28
+ { id: "integrations", title: "Integrations", desc: "Request sources, your Google account, and web research.", ico: "ext" },
29
+ { id: "mobile", title: "Phone", desc: "Open kaizen from your phone, and send files to WhatsApp.", ico: "phone" },
28
30
  ]],
29
31
  ];
32
+ // Pages that were merged into another: an old `?page=` address still opens the right one.
33
+ const PAGE_ALIAS: Record<string, string> = { voice: "keyboard", shortcuts: "keyboard" };
34
+ export const pageId = (id: string) => PAGE_ALIAS[id] ?? id;
35
+ // Subsections that should come first on their page, whatever order their rows arrive in.
36
+ export const SUB_ORDER: Record<string, string[]> = { general: ["Storage", "Folders", "App"], keyboard: ["Shortcuts", "Dictation"] };
30
37
  // First match wins: [key pattern, page, subsection].
31
38
  const PLACES: [RegExp, string, string][] = [
32
- [/^(preset|runner|explore\.|build\.|review\.executor)/, "agents", "Workflow"],
33
- [/^(subagents\.|agent\.model\.)/, "agents", "Models"],
34
- [/^agent\.handoff_model\./, "agents", "Handoff session"],
39
+ [/^(preset|runner|explore\.|build\.|review\.executor)/, "runs", "Workflow"],
40
+ [/^review\.(write_memory|memory_max_lines)$/, "runs", "Memory"],
41
+ [/^(subagents\.|agent\.model\.)/, "models", "Models"],
42
+ [/^agent\.handoff_model\./, "models", "Handoff session"],
35
43
  [/^agent\.default$/, "agents", "Default agent"],
36
44
  [/^agent\./, "agents", "Running agents"],
37
45
  [/^orchestration\./, "orchestration", "Workers"],
38
- [/^dictation\./, "voice", "Dictation"],
46
+ [/^dictation\./, "keyboard", "Dictation"],
39
47
  [/^sources\./, "integrations", "Request sources"],
40
48
  [/^(mode|approvals\.|auto_accept)/, "approvals", "Approvals"],
41
49
  [/^auto_fix\./, "autofix", "Auto-fix"],
42
50
  [/^auto_guard\./, "autofix", "Auto mode guard"],
43
51
  [/^git\./, "git", "Git"],
44
52
  [/^ui\./, "terminal", "Terminal"],
45
- [/^board\.chat_hotkey$/, "shortcuts", "Shortcuts"],
53
+ [/^board\.chat_hotkey$/, "keyboard", "Shortcuts"],
54
+ [/^board\.(projects_dir|video_dir)$/, "general", "Folders"],
46
55
  [/^board\./, "general", "App"],
47
- [/^(review\.|state\.)/, "general", "Project"],
56
+ [/^state\./, "general", "Storage"],
48
57
  ];
49
58
  // A setting nobody has placed yet still shows, on General.
50
59
  export const placeOf = (key: string): [string, string] => {
@@ -14,7 +14,7 @@ import { skillRows, wireSkills } from "./settings-skills.ts";
14
14
  import { mountPhone } from "./phone-setup.ts";
15
15
  import { mountWhatsApp } from "./whatsapp-setup.ts";
16
16
  import { fillMics, micRow } from "./settings-voice.ts";
17
- import { placeOf, SETTINGS_NAV } from "./settings-pages.ts";
17
+ import { pageId, placeOf, SETTINGS_NAV, SUB_ORDER } from "./settings-pages.ts";
18
18
  import { askNotify, notifyOn, playSound, soundPick, SOUNDS, toast } from "./toast.ts";
19
19
  import { updBar } from "./update.ts";
20
20
  import { go, view } from "./views.ts";
@@ -55,35 +55,28 @@ export async function openSettings() {
55
55
  $("pfoot").innerHTML = "";
56
56
  const cur = document.documentElement.dataset.theme || "system";
57
57
  const colour = document.documentElement.dataset.color || "monochrome";
58
- let cfg = await fetch("/settings?scope=" + encodeURIComponent(store.setScope))
59
- .then((r) => (r.ok ? r.json() : null))
60
- .catch(() => null);
58
+ // Everything the page shows, asked for at once.
59
+ const get = (url: string, init?: RequestInit) =>
60
+ fetch(url, init)
61
+ .then((r) => (r.ok ? r.json() : null))
62
+ .catch(() => null);
63
+ let [cfg, gg, rk, ap, ac, sk, au, cl] = await Promise.all([
64
+ get("/settings?scope=" + encodeURIComponent(store.setScope)),
65
+ get("/google"),
66
+ get("/research-key"),
67
+ get("/agent-prefs"),
68
+ get("/accounts"),
69
+ get("/skills"),
70
+ get("/automations", { headers: dirHeader() }),
71
+ get("/cleanup", { headers: dirHeader() }),
72
+ ]);
73
+ gg ??= {};
61
74
  // A project the board no longer knows: fall back to All projects.
62
75
  if (!cfg && store.setScope !== "all") {
76
+ if (gen !== store.pageGen) return;
63
77
  store.setScope = "all";
64
78
  return openSettings();
65
79
  }
66
- const gg = await fetch("/google")
67
- .then((r) => r.json())
68
- .catch(() => ({}));
69
- const rk = await fetch("/research-key")
70
- .then((r) => (r.ok ? r.json() : null))
71
- .catch(() => null);
72
- const ap = await fetch("/agent-prefs")
73
- .then((r) => (r.ok ? r.json() : null))
74
- .catch(() => null);
75
- const ac = await fetch("/accounts")
76
- .then((r) => (r.ok ? r.json() : null))
77
- .catch(() => null);
78
- const sk = await fetch("/skills")
79
- .then((r) => (r.ok ? r.json() : null))
80
- .catch(() => null);
81
- const au = await fetch("/automations", { headers: dirHeader() })
82
- .then((r) => (r.ok ? r.json() : null))
83
- .catch(() => null);
84
- const cl = await fetch("/cleanup", { headers: dirHeader() })
85
- .then((r) => (r.ok ? r.json() : null))
86
- .catch(() => null);
87
80
  if (gen !== store.pageGen) return;
88
81
  $("psub").textContent = "";
89
82
  $("psub").title = "";
@@ -117,22 +110,14 @@ export async function openSettings() {
117
110
  const nton = notifyOn();
118
111
  const ntHelp = !nton ? "Off in this browser" : np === "granted" ? "" : np === "denied" ? "Pop-ups blocked by this browser; the sound still plays" : np ? "Pop-ups wait for the browser to ask; the sound still plays" : "Pop-ups not supported here; the sound still plays";
119
112
  // Each page's subsections, in the order they first appear.
120
- const pageRows = new Map<string, Map<string, unknown[]>>(PAGES.map((p) => [p.id, new Map()]));
113
+ const pageRows = new Map<string, Map<string, unknown[]>>(PAGES.map((p) => [p.id, new Map((SUB_ORDER[p.id] ?? []).map((sub) => [sub, []]))]));
121
114
  const put = (page, sub, r) => {
122
115
  const m = pageRows.get(page);
123
116
  if (!m.has(sub)) m.set(sub, []);
124
117
  m.get(sub).push(r);
125
118
  };
126
119
  const defaultAgent = cfg?.rows.find((r) => r.key === "agent.default")?.value ?? "auto";
127
- if (cl) for (const r of cleanupRows(cl)) put("general", "Cleanup", row(r.label, r.control, r.hint, r.id, r.q));
128
120
  if (cfg) {
129
- put("general", "Scope", row(
130
- "Settings for",
131
- html`<select class="sel" id="s-scope">${[{ dir: "all", label: "All projects" }, ...cfg.projects].map((p) => html`<option value="${p.dir}"${p.dir === cfg.scope ? " selected" : ""}>${p.label}</option>`)}</select>`,
132
- scoped ? "This project's own .kaizen/config.yml; anything it does not set comes from All projects." : "~/.kaizen/config.yml; a project's own config wins where it sets a value.",
133
- "s-scope",
134
- "settings for scope project all projects",
135
- ));
136
121
  // Drawn as chips with the agent list, above the rest of the page.
137
122
  cfg.rows = cfg.rows.filter((r) => !(r.key === "agent.default" && ap));
138
123
  // A model row only for a tool on this machine.
@@ -157,10 +142,12 @@ export async function openSettings() {
157
142
  ));
158
143
  }
159
144
  }
160
- put("voice", "Dictation", row("Microphone", micRow(), "Used by this browser. Names appear after you first allow the microphone. Ctrl+Alt+D dictates into the focused terminal.", "v-mic", "microphone input device mic dictation shortcut"));
145
+ // Under Runs to keep, which they act on.
146
+ if (cl) for (const r of cleanupRows(cl)) put("general", "Storage", row(r.label, r.control, r.hint, r.id, r.q));
147
+ put("keyboard", "Dictation", row("Microphone", micRow(), "Used by this browser. Names appear after you first allow the microphone. Ctrl+Alt+D dictates into the focused terminal.", "v-mic", "microphone input device mic dictation shortcut"));
161
148
  put("mobile", "Phone", html`
162
149
  <div class="srow ph-card" data-q="phone mobile tailscale qr connect address setup"><div id="phset"></div></div>
163
- <div class="srow ph-card" style="margin-top:16px" data-q="whatsapp phone mobile qr message send"><div id="waset"></div></div>
150
+ <div class="srow ph-card" data-q="whatsapp phone mobile qr message send"><div id="waset"></div></div>
164
151
  `);
165
152
  put("integrations", "Google", row("OAuth client id", html`<input class="sel" id="gg-id" placeholder="${gg.hasClient ? "Saved. Paste a new one to replace it" : "Desktop app client id from Google Cloud"}" spellcheck="false" autocomplete="off">`, "", "gg-id", "google oauth client id sheets write back"));
166
153
  put("integrations", "Google", row("OAuth client secret", html`<span class="fpick"><input class="sel" id="gg-secret" type="password" placeholder="${gg.hasClient ? "Saved. Paste a new one to replace it" : ""}" spellcheck="false" autocomplete="off"><button class="btn" id="gg-save" type="button">Save</button></span>`, "", "gg-secret", "google oauth client secret"));
@@ -197,7 +184,7 @@ export async function openSettings() {
197
184
  put("notifications", "Browser", row("Haptic feedback", toggleSwitch(hapton, { sm: true, attrs: { id: "hp" } }), "A light tick when you tap something on a phone.", "hp", "haptic feedback vibrate vibration touch tap phone browser"));
198
185
  put("notifications", "Browser", row("Notification sound", ctl("ns", SOUNDS, soundPick()), "Plays with each notice. Changing it plays it.", "ns", "notification sound audio browser " + SOUNDS.join(" "), !nton));
199
186
  // A narrow screen starts on the list of pages, a wide one on the first page.
200
- store.setPage ??= new URLSearchParams(location.search).get("page") || "";
187
+ store.setPage = pageId(store.setPage ?? new URLSearchParams(location.search).get("page") ?? "");
201
188
  const scopeName = scoped ? cfg.projects.find((p) => p.dir === cfg.scope)?.label : "";
202
189
  // A save redraws the page: the rows stay where they were scrolled to.
203
190
  const top = $("smain")?.scrollTop || 0;
@@ -205,14 +192,18 @@ export async function openSettings() {
205
192
  <nav class="snav" aria-label="Settings">
206
193
  <button class="sback" id="sback" type="button">${ico("chev")}Back to app</button>
207
194
  <div class="sq"><input class="sel" id="sq" type="search" placeholder="Search settings" aria-label="Search settings" spellcheck="false" autocomplete="off" value="${store.setQ}"></div>
208
- <div class="snavs">${SETTINGS_NAV.map(([g, ps]) => html`<div class="snavg"><p>${g}</p>${ps.map((p) => html`<button type="button" data-page="${p.id}">${ico(p.ico)}<span>${p.title}</span></button>`)}</div>`)}</div>
195
+ ${cfg ? html`<div class="sacct" title="${scoped ? "This project's own .kaizen/config.yml; anything it does not set comes from All projects." : "~/.kaizen/config.yml; a project's own config wins where it sets a value."}">
196
+ <span class="stile">${ico(scoped ? "board" : "home")}</span>
197
+ <span class="sacct-t"><small id="s-scope-l">Settings for</small><select class="sel" id="s-scope" aria-labelledby="s-scope-l">${[{ dir: "all", label: "All projects" }, ...cfg.projects].map((p) => html`<option value="${p.dir}"${p.dir === cfg.scope ? " selected" : ""}>${p.label}</option>`)}</select><small>${scoped ? "Overrides All projects" : "Every project"}</small></span>
198
+ </div>` : ""}
199
+ <div class="snavs">${SETTINGS_NAV.map(([g, ps]) => html`<div class="snavg" role="group" aria-label="${g}">${ps.map((p) => html`<button type="button" data-page="${p.id}"><span class="stile">${ico(p.ico)}</span><span>${p.title}</span></button>`)}</div>`)}</div>
209
200
  </nav>
210
201
  <div class="smain" id="smain">
211
202
  ${PAGES.map((p) => html`<div class="spage" data-page="${p.id}">
212
203
  <button class="sup" type="button">${ico("chev")}Settings</button>
213
- <header><h2>${p.title}</h2><p>${p.desc}${scopeName ? ` Editing ${scopeName}.` : ""}</p></header>
204
+ <header><span class="stile">${ico(p.ico)}</span><div><h2>${p.title}</h2><p>${p.desc}${scopeName ? ` Editing ${scopeName}.` : ""}</p></div></header>
214
205
  ${p.id === "general" ? html`<div id="supd"></div>` : ""}
215
- <div class="scard">${p.id === "agents" && ap ? agentRows(ap, defaultAgent, scopeName) : ""}${p.id === "accounts" && ac ? accountRows(ac) : ""}${p.id === "orchestration" && cfg ? orchestrationRows({ windows: !!cfg.windows, bypass: cfg.rows.some((r) => r.key === "orchestration.permissions" && r.value === "bypass") }) : ""}${p.id === "skills" && sk ? skillRows(sk.skills) : ""}${p.id === "automations" ? (au ? automationRows(au) : html`<h3 class="sg">Automations</h3><div class="sgrp"><div class="sk" data-q="automation">Open a project to add automations. They belong to one project each.</div></div>`) : ""}${[...pageRows.get(p.id)].map(([sub, rows]) => html`<h3 class="sg">${sub}</h3><div class="sgrp">${rows}</div>`)}</div>
206
+ <div class="scard">${p.id === "agents" && ap ? agentRows(ap, defaultAgent, scopeName) : ""}${p.id === "accounts" && ac ? accountRows(ac) : ""}${p.id === "orchestration" && cfg ? orchestrationRows({ windows: !!cfg.windows, bypass: cfg.rows.some((r) => r.key === "orchestration.permissions" && r.value === "bypass") }) : ""}${p.id === "skills" && sk ? skillRows(sk.skills) : ""}${p.id === "automations" ? (au ? automationRows(au) : html`<h3 class="sg">Automations</h3><div class="sgrp"><div class="sk" data-q="automation">Open a project to add automations. They belong to one project each.</div></div>`) : ""}${[...pageRows.get(p.id)].filter(([, rows]) => rows.length).map(([sub, rows]) => html`<h3 class="sg">${sub}</h3><div class="sgrp">${rows}</div>`)}</div>
216
207
  </div>`)}
217
208
  ${cfg ? "" : html`<p class="snone">Settings could not be read. Run <code>kaizen settings</code>.</p>`}
218
209
  <p class="snone" id="snone" hidden></p>
@@ -38,7 +38,7 @@ export const markView = (v) => {
38
38
  : v === "home"
39
39
  ? isPhone()
40
40
  ? "kaizen"
41
- : "Home"
41
+ : "Chat"
42
42
  : v === "chat"
43
43
  ? "Chat"
44
44
  : v === "device"
@@ -1,4 +1,4 @@
1
- // The WhatsApp card: Settings → Mobile. Walks the user through linking WhatsApp Web,
1
+ // The WhatsApp card: Settings → Phone. Walks the user through linking WhatsApp Web,
2
2
  // displaying a QR code that connects to the background Baileys bridge.
3
3
  import { html, raw } from "./dom.ts";
4
4
 
@@ -9,7 +9,8 @@ import { initResources } from "./resources.ts";
9
9
  import { age, need } from "./labels.ts";
10
10
  import { openAdd } from "./add-project.ts";
11
11
  import { initSearch } from "./search.ts";
12
- import { agentsHtml, dueWord, forgetAgents, gitDue, settleIn, toggleOpen, wsAgents, type Agent } from "./ws-tabs.ts";
12
+ import { agentsHtml, dueWord, forgetAgents, gitDue, moveTo, settleIn, toggleOpen, wsAgents, type Agent } from "./ws-tabs.ts";
13
+ import { toast } from "./toast.ts";
13
14
 
14
15
  const DAY = 864e5;
15
16
  const STAGE = ["idea", "planning", "building", "reviewing", "done"];
@@ -195,7 +196,10 @@ export function wsOfCard(c, projects = last.projects) {
195
196
  const ws = projects?.find((p) => p.dir === c.state)?.workspaces ?? [];
196
197
  return ws.find((w) => w.path === c.ws)?.path ?? ws.find((w) => w.main)?.path ?? c.ws ?? "";
197
198
  }
198
- export const wsHref = (dir, ws) => `/?view=ws&dir=${encodeURIComponent(dir)}&ws=${encodeURIComponent(ws)}`;
199
+ // The floating Home workspace's folder (~/.kaizen/home): never a project's `.kaizen` state dir, and it has no workspace view.
200
+ export const isHomeDir = (d: unknown) => typeof d === "string" && /[\\/]\.kaizen[\\/]home$/.test(d);
201
+ // A Home terminal's address opens the board with its panel (web/board/home-ws.ts), from any page.
202
+ export const wsHref = (dir, ws) => (isHomeDir(dir) ? "/?view=board&homews=1" : `/?view=ws&dir=${encodeURIComponent(dir)}&ws=${encodeURIComponent(ws)}`);
199
203
  export const RANK = { wait: 0, plan: 1, build: 2, review: 3, stalled: 4, idle: 5, done: 6, aband: 7 };
200
204
  export const folderOf = (w) => w.path.split(/[\\/]/).pop() || w.path;
201
205
  // A worktree's mark on line 2 of its card.
@@ -212,10 +216,85 @@ async function readTaskAttention() {
212
216
  }
213
217
  const taskLinks = (dir: string, w: any, cards: any[]) => (attentionTasks ?? []).filter((t) => t.dir === dir && !t.legacy && t.attention.category !== "completed" && filt.running && t.status !== "draft" && (cards.some((c) => taskForCard(c)?.id === t.id) || (w.main && !(t.runs ?? t.runIds ?? []).length))).sort((a: any, b: any) => (a.created ?? 0) - (b.created ?? 0)).map((t) => html`<a class="rtask" href="/?view=task&task=${encodeURIComponent(t.id)}&dir=${encodeURIComponent(t.dir)}" data-task-id="${t.id}" data-task-dir="${t.dir}" title="${t.attention.reason} · ${t.attention.action}"><span class="si ${t.attention.category === "needs-you" ? "wait" : t.attention.category === "completed" ? "done" : ["interrupted", "failed"].includes(t.status ?? "") ? "stalled" : t.status === "draft" ? "idle" : "build"}"></span><span><b>${t.title}</b><small>${t.attention.reason}</small></span></a>`);
214
218
 
219
+ // ---- ranking projects: press a project's bar and drag it up or down (pointer events, so a mouse
220
+ // and a finger work alike). A mouse starts after 5 px of movement; a finger after a 300 ms hold
221
+ // without moving, so a quick swipe still scrolls the sidebar. A line shows where it will land;
222
+ // letting go saves the order for every device (POST /projects/order rewrites ~/.kaizen/projects).
223
+ // Escape or a cancelled pointer puts it back. The click that ends a drag does not fold.
224
+ let ranking = false, rankDirty = false, rankClick = false;
225
+ function rankDrag(box: HTMLElement) {
226
+ let d: { dir: string; bar: HTMLElement; id: number; x: number; y: number; hold?: ReturnType<typeof setTimeout>; to: number } | null = null;
227
+ const groups = () => [...box.querySelectorAll<HTMLElement>(":scope > .pgrp")];
228
+ const clear = () => {
229
+ groups().forEach((g) => g.classList.remove("rank-before"));
230
+ box.classList.remove("rank-end");
231
+ d?.bar.classList.remove("rank-lift");
232
+ };
233
+ const end = (save: boolean) => {
234
+ if (!d) return;
235
+ clearTimeout(d.hold);
236
+ const was = ranking, { dir, to } = d;
237
+ clear();
238
+ d = null;
239
+ ranking = false;
240
+ if (was) rankClick = true; // the click that follows this pointerup
241
+ if (was && save) {
242
+ const dirs = groups().map((g) => g.querySelector<HTMLElement>(".proj")!.dataset.proj!);
243
+ const from = dirs.indexOf(dir);
244
+ if (from >= 0 && to !== from && to !== from + 1) {
245
+ const next = moveTo(dirs, from, to);
246
+ const rank = new Map(next.map((x, i) => [x, i]));
247
+ last.projects = [...(last.projects ?? [])].sort((a, b) => (rank.get(a.dir) ?? 1e9) - (rank.get(b.dir) ?? 1e9));
248
+ void fetch("/projects/order", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ dirs: next }) })
249
+ .then((r) => { if (!r.ok) toast("Could not save the project order"); })
250
+ .catch(() => toast("Could not save the project order"));
251
+ }
252
+ }
253
+ if (was || rankDirty) (rankDirty = false), drawList();
254
+ if (was) setTimeout(() => (rankClick = false), 0);
255
+ };
256
+ const start = () => {
257
+ if (!d) return;
258
+ ranking = true;
259
+ d.bar.classList.add("rank-lift");
260
+ try { d.bar.setPointerCapture(d.id); } catch {}
261
+ navigator.vibrate?.(8);
262
+ };
263
+ box.addEventListener("pointerdown", (e) => {
264
+ const bar = (e.target as HTMLElement).closest<HTMLElement>(".pgrp > .proj");
265
+ if (!bar || e.button !== 0 || bar.parentElement?.parentElement !== box) return;
266
+ d = { dir: bar.dataset.proj!, bar, id: e.pointerId, x: e.clientX, y: e.clientY, to: -1 };
267
+ if (e.pointerType !== "mouse") d.hold = setTimeout(start, 300);
268
+ });
269
+ box.addEventListener("pointermove", (e) => {
270
+ if (!d || e.pointerId !== d.id) return;
271
+ const far = Math.hypot(e.clientX - d.x, e.clientY - d.y);
272
+ if (!ranking) {
273
+ if (e.pointerType === "mouse" ? far > 5 : far > 8) e.pointerType === "mouse" ? start() : end(false);
274
+ if (!ranking) return;
275
+ }
276
+ e.preventDefault();
277
+ // The landing slot: before the first project whose bar's middle is below the pointer, else the end.
278
+ const gs = groups();
279
+ const i = gs.findIndex((g) => { const r = g.getBoundingClientRect(); return e.clientY < r.top + r.height / 2; });
280
+ d.to = i < 0 ? gs.length : i;
281
+ gs.forEach((g, k) => g.classList.toggle("rank-before", k === d!.to));
282
+ box.classList.toggle("rank-end", d.to === gs.length);
283
+ });
284
+ box.addEventListener("pointerup", (e) => d && e.pointerId === d.id && end(true));
285
+ box.addEventListener("pointercancel", () => end(false));
286
+ // A held finger: no page scroll and no long-press menu while it drags.
287
+ box.addEventListener("touchmove", (e) => { if (ranking) e.preventDefault(); }, { passive: false });
288
+ box.addEventListener("contextmenu", (e) => { if (d) e.preventDefault(); }, true);
289
+ addEventListener("keydown", (e) => { if (ranking && e.key === "Escape") (e.preventDefault(), end(false)); });
290
+ }
291
+
215
292
  export const wsLabel = (w) => w.branch || (w.main ? "workspace" : w.path.split(/[\\/]/).pop());
216
293
  function drawList() {
217
294
  const box = $("plist");
218
295
  if (!box) return;
296
+ // A drag in progress owns the list: a redraw would pull the bar out from under the pointer.
297
+ if (ranking) return void (rankDirty = true);
219
298
  const now = Date.now();
220
299
  const projects = (last.projects ?? []).filter((p) => p.workspaces?.length);
221
300
  const all = new Set(projects.map((p) => p.dir));
@@ -251,9 +330,8 @@ function drawList() {
251
330
  return { p, rows, top: Math.min(9, ...rows.map((r) => top(r.cs))) };
252
331
  })
253
332
  // Running only keeps every project listed, so an idle one reads "Nothing running" rather than vanishing.
254
- .filter((g) => g.rows.length || filt.running)
255
- // Projects by their most urgent card; the picker's order otherwise.
256
- .sort((a, b) => a.top - b.top);
333
+ // In the registry's order, which the user ranks by dragging a project's bar (rankDrag below).
334
+ .filter((g) => g.rows.length || filt.running);
257
335
 
258
336
  const f = $("pfilter");
259
337
  const on = filt.dirs.some((d) => all.has(d)) || !filt.running || filt.done;
@@ -275,7 +353,7 @@ function drawList() {
275
353
  // A + for a new worktree on git projects (the main checkout has a branch).
276
354
  const git = p.workspaces.some((w) => w.branch);
277
355
  const mainWs = p.workspaces?.find((w) => w.main)?.path ?? p.workspaces?.[0]?.path ?? dir;
278
- return html`<div class="pgrp"><button type="button" class="proj${shut ? " shut" : ""}" data-proj="${dir}" data-ws="${mainWs}" data-fold="${dir}" title="${dir}" aria-expanded="${String(!shut)}">${logo(dir, name, last.projects)}<span class="pname">${name}</span><svg class="fchev" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>${git ? html`<button type="button" class="wadd" data-wadd="${dir}" title="New workspace in ${name}" aria-label="New workspace in ${name}"><svg aria-hidden="true"><use href="#i-plus"/></svg></button>` : ""}</div>${shut ? "" : raw('<div class="pws">')}${shut ? "" : rows.map(({ w, cs }) => {
356
+ return html`<div class="pgrp"><button type="button" class="proj${shut ? " shut" : ""}" data-proj="${dir}" data-ws="${mainWs}" data-fold="${dir}"${rows.length ? "" : " data-empty"} title="${dir}" aria-expanded="${String(!shut)}">${logo(dir, name, last.projects)}<span class="pname">${name}</span><svg class="fchev" viewBox="0 0 24 24" aria-hidden="true"><path d="M9 6l6 6-6 6" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg></button>${git ? html`<button type="button" class="wadd" data-wadd="${dir}" title="New workspace in ${name}" aria-label="New workspace in ${name}"><svg aria-hidden="true"><use href="#i-plus"/></svg></button>` : ""}</div>${shut ? "" : raw('<div class="pws">')}${shut ? "" : rows.map(({ w, cs }) => {
279
357
  // The dot: the most urgent run there, or an agent asking (amber) or working (spinner).
280
358
  const rows = shownAgents(wsAgents(last.agents ?? [], dir, w.path, wsOfCard, now));
281
359
  const st0 = cs.length ? stateOf([...cs].sort((a, b) => RANK[stateOf(a)] - RANK[stateOf(b)])[0]) : "";
@@ -293,6 +371,7 @@ function drawList() {
293
371
  if (a) wsMenu(e, a);
294
372
  };
295
373
  box.onclick = (e) => {
374
+ if (rankClick) return void ((rankClick = false), e.preventDefault(), e.stopPropagation());
296
375
  const t = e.target as HTMLElement;
297
376
  const task = t.closest<HTMLElement>("[data-task-id]");
298
377
  if (task) {
@@ -311,11 +390,12 @@ function drawList() {
311
390
  const d = t.closest<HTMLElement>("[data-fold]")?.dataset.fold;
312
391
  if (d) return void (e.preventDefault(), fold(d));
313
392
  }
314
- const proj = t.closest<HTMLElement>("[data-proj]");
393
+ // A project bar folds and unfolds, like a folder. One that lists nothing has no rows to click,
394
+ // so it opens its main workspace instead.
395
+ const proj = t.closest<HTMLElement>("[data-proj][data-empty]");
315
396
  if (proj) {
316
397
  e.preventDefault();
317
398
  const dir = proj.dataset.proj!, ws = proj.dataset.ws || dir;
318
- if (folded.has(dir)) fold(dir);
319
399
  if (ask("kz-open-ws", { dir, ws })) return;
320
400
  }
321
401
  const d = t.closest<HTMLElement>("[data-fold]")?.dataset.fold;
@@ -438,6 +518,7 @@ export function initRail() {
438
518
  });
439
519
  }).observe(document.body, { childList: true, subtree: true });
440
520
  if (!$("plist")) return;
521
+ rankDrag($("plist"));
441
522
  addEventListener("kz-task-attention", drawList);
442
523
  void readTaskAttention();
443
524
  onBoardCards((cards, projects, agents) => {
@@ -147,6 +147,21 @@ export function devUrl(pv: string | null | undefined, ports: number[]): string |
147
147
  // yet opened the Browser: once per run id (`seen`).
148
148
  export const toOpen = (cards: any[], was: Set<string>, seen: string[], keyOf: (c) => string) => cards.filter((c) => reviewing(c) && !was.has(keyOf(c)) && !seen.includes(keyOf(c)));
149
149
 
150
+ // The list with the item at `from` moved into slot `to` (0 = top, list.length = the end), counted
151
+ // before the move: the sidebar's project drag lands it where its drop line was drawn.
152
+ export const moveTo = <T>(list: T[], from: number, to: number): T[] => {
153
+ const out = list.filter((_, i) => i !== from);
154
+ out.splice(to > from ? to - 1 : to, 0, list[from]);
155
+ return out;
156
+ };
157
+
158
+ // `kaizen preview` written from folder `pws` belongs to workspace `ws`: the same folder or one inside
159
+ // it, but never a worktree under it (`.kaizen/wt/`), which is a workspace of its own.
160
+ export const previewIn = (pws: string, ws: string) => pws === ws || (pws.startsWith(ws + "/") && !pws.startsWith(ws + "/.kaizen/wt/"));
161
+ // A preview opens a tab only when written after the last one this visit recorded; the first look at
162
+ // a workspace (`last` undefined: a click, a switch, a reload) only records.
163
+ export const previewOpens = (at: number, last: number | undefined) => last !== undefined && at > last;
164
+
150
165
  // ---- the sidebar card's agents (/state `agents`, one entry per open agent terminal)
151
166
  export type Agent = { key: string; dir: string; ws?: string; agent?: string; name: string; run?: string; asking: boolean; busy: boolean; last?: string; at?: number; born?: number; land?: string };
152
167
  export type Status = "conflict" | "failed" | "asking" | "working" | "done";