kaizen-agent 1.50.0 → 1.52.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.
@@ -0,0 +1,399 @@
1
+ import { open } from "./panel.ts";
2
+ import { pick, short } from "./projects.ts";
3
+ import { $, html, ico, raw, vt } from "./dom.ts";
4
+ import { draft, DK } from "./drafts.ts";
5
+ import { md } from "./markdown.ts";
6
+ import { store } from "./store.ts";
7
+ import { toast } from "./toast.ts";
8
+
9
+ // ---- Home: a chat with kaizen's main agent (cli/chat.ts). Chats are not tied to the
10
+ // board's project: each is in a project or in none, and the agent can move it. A new chat
11
+ // starts in the project picked above (none in All projects); the board follows the open chat.
12
+ let chats = [];
13
+ let cur = null; // the open chat, as /chat returns it; null is a new one
14
+ let sending = false;
15
+ let remoteBusy = false;
16
+ let poll = null;
17
+ let seen = 0; // messages already on screen: only newer ones animate in
18
+ let shown = null; // the chat those were from
19
+ let following = true; // scrolling up pauses auto-follow until the reader reaches the bottom again
20
+ let attachments = [];
21
+
22
+ // The chat list beside the conversation: open or closed, kept per browser. A phone opens it as a drawer, closed at first.
23
+ const phone = () => matchMedia("(max-width:640px)").matches;
24
+ // Read when Home first draws, not at import: tests load this module with no window.
25
+ let side = null;
26
+ const sideAtStart = () => {
27
+ try {
28
+ return !phone() && localStorage.getItem("kz-hist") !== "0";
29
+ } catch (e) {
30
+ return !phone();
31
+ }
32
+ };
33
+ function setSide(on) {
34
+ side = on;
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");
38
+ if (!phone())
39
+ try {
40
+ localStorage.setItem("kz-hist", on ? "1" : "0");
41
+ } catch (e) {}
42
+ }
43
+
44
+ const get = (u) => fetch(u).then((r) => r.json());
45
+ const post = (u, b) => fetch(u, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(b) });
46
+ const remember = (id) => { try { id ? sessionStorage.setItem("kz-chat", id) : sessionStorage.removeItem("kz-chat"); } catch (e) {} };
47
+ // The project a new chat starts in: the board's, unless it shows every project or none.
48
+ const here = () => (store.S.all || !store.S.dir || !(store.S.projects || []).some((p) => p.dir === store.S.dir) ? null : store.S.dir);
49
+ const name = (d) => short((store.S.projects || []).find((p) => p.dir === d)?.label || String(d).replace(/[\\/]\.kaizen$/, ""));
50
+ // The board follows the chat into its project.
51
+ const follow = (d) => d && d !== store.S.dir && pick(d);
52
+
53
+ const SUGGEST = ["What's waiting on me?", "Summarize what changed this week", "Plan a new feature: ", "Review my last change"];
54
+ // Run ids the agent named that are cards on this board: each becomes a button to its card.
55
+ const runsIn = (t) =>
56
+ [...new Set(String(t).match(/\b\d{4}-\d{2}-\d{2}-[a-z0-9-]+\b/g) || [])].filter((id) =>
57
+ store.S.cards.some((c) => c.kind === "run" && c.id === id),
58
+ );
59
+
60
+ function msg(m, i) {
61
+ const anim = i >= seen ? " in" : "";
62
+ if (m.role === "user") return html`<div class="hm u${anim}">${m.text ? html`<div class="hb">${m.text}</div>` : ""}${m.files?.length ? html`<div class="hfiles">${m.files.map((f) => html`<span>${ico("clip")}${f.name}</span>`)}</div>` : ""}</div>`;
63
+ const active = i === cur.messages.length - 1 && (sending || remoteBusy);
64
+ const steps = (m.steps || []).map(
65
+ (s) => html`<li class="${s.ok === false ? "bad" : ""}">${ico(s.kind === "edit" ? "note" : s.kind === "project" ? "board" : "term")}<code>${s.text}</code></li>`,
66
+ );
67
+ // A move is news, not a detail: shown under the reply as well as in the steps.
68
+ const moved = (m.steps || []).filter((s) => s.kind === "project");
69
+ const runs = runsIn(m.text + " " + (m.steps || []).map((s) => s.text).join(" "));
70
+ // Nothing yet: the typing dots stand in for the reply.
71
+ if (!steps.length && !m.text && !m.error && !active) return "";
72
+ return html`<div class="hm a${anim}">${steps.length ? html`<details class="hsteps"${m.text ? "" : " open"}><summary>${steps.length} step${steps.length > 1 ? "s" : ""}</summary><ul>${steps}</ul></details>` : ""}${m.text ? html`<div class="hb md">${raw(md(m.text))}</div>` : ""}${m.error ? html`<div class="herr">${m.error}</div>` : ""}${moved.map((s) => html`<div class="hmove${s.ok === false ? " bad" : ""}">${ico("board")}${s.text}</div>`)}${runs.map((id) => html`<button class="btn ghost sm hrun" data-run="${id}">${ico("board")}Open ${id}</button>`)}${active ? html`<div class="hactivity" role="status"><span class="hmascot"><img src="/logo.png" alt="" aria-hidden="true"><i class="hlaptop"></i></span><span class="hactivity-copy"><span>${m.activity || "Thinking…"}</span><span class="hdots" aria-hidden="true"><i></i><i></i><i></i></span></span></div>` : ""}</div>`;
73
+ }
74
+
75
+ function hero() {
76
+ const d = here();
77
+ return html`<div class="hhero"><h2>${d ? html`What should we do in ${name(d)}?` : "What should we work on?"}</h2><p class="hint">${d ? "Ask about this project or another one, or start a new one." : "Name a project, or describe a new one and the agent will set it up."} Bigger work becomes a kaizen run on the Board.</p></div>`;
78
+ }
79
+
80
+ function chips() {
81
+ return html`<div class="hchips">${SUGGEST.map((s) => html`<button class="chip" data-s="${s}">${s}</button>`)}</div>`;
82
+ }
83
+
84
+ function list() {
85
+ return html`<div class="hsin"><div class="hshd"><span>Chats</span><button class="ib sm" id="hclose" aria-label="Hide chats" title="Hide chats">${ico("side")}</button></div><nav class="hlist" aria-label="Chats">${chats.map((c) => html`<div class="hli${cur && cur.id === c.id ? " on" : ""}"><button data-c="${c.id}" title="${c.title}">${c.busy ? html`<span class="dot"></span>` : ""}<span class="ht">${c.title}</span><span class="hp">${c.project ? name(c.project) : "No project"}</span></button><button class="ib sm" data-del="${c.id}" aria-label="Delete chat: ${c.title}" title="Delete chat">${ico("trash")}</button></div>`)}</nav></div>`;
86
+ }
87
+
88
+ function bindReply(root) {
89
+ root.querySelectorAll(".md a").forEach((a) => {
90
+ if (/^https?:/i.test(a.getAttribute("href") || "")) (a.target = "_blank"), (a.rel = "noopener noreferrer");
91
+ else a.replaceWith(Object.assign(document.createElement("span"), { textContent: a.textContent, title: a.getAttribute("href") || "" }));
92
+ });
93
+ root.querySelectorAll("[data-run]").forEach(
94
+ (b) =>
95
+ (b.onclick = () => {
96
+ const c = store.S.cards.find((x) => x.kind === "run" && x.id === b.dataset.run);
97
+ if (c) open(c); // open() moves to the board
98
+ }),
99
+ );
100
+ }
101
+
102
+ function updateReply(reply) {
103
+ const log = $("hlog");
104
+ const last = log?.lastElementChild;
105
+ if (!last?.classList.contains("hm") || !last.classList.contains("a")) return draw();
106
+ const top = log.scrollTop;
107
+ const stepsOpen = last.querySelector(".hsteps")?.open;
108
+ const markup = String(msg(reply, cur.messages.length - 1));
109
+ if (!markup) { last.remove(); log.scrollTop = following ? log.scrollHeight : top; return; }
110
+ const next = document.createElement("div");
111
+ next.innerHTML = markup;
112
+ last.replaceChildren(...next.firstElementChild.childNodes);
113
+ if (stepsOpen !== undefined && last.querySelector(".hsteps")) last.querySelector(".hsteps").open = stepsOpen;
114
+ bindReply(last);
115
+ log.scrollTop = following ? log.scrollHeight : top;
116
+ }
117
+
118
+ function bindChatItems(root) {
119
+ root.querySelectorAll("[data-c]").forEach(
120
+ (b) =>
121
+ (b.onclick = () => {
122
+ if (phone()) side = false;
123
+ show(b.dataset.c);
124
+ }),
125
+ );
126
+ root.querySelectorAll("[data-del]").forEach(
127
+ (b) =>
128
+ (b.onclick = async () => {
129
+ if (!confirm("Delete this chat?")) return;
130
+ const r = await post("/chat/delete", { id: b.dataset.del });
131
+ if (!r.ok) return toast((await r.json()).error);
132
+ if (cur && cur.id === b.dataset.del) { cur = null; remoteBusy = false; remember(null); }
133
+ refresh();
134
+ }),
135
+ );
136
+ }
137
+
138
+ function drawList() {
139
+ const old = $("home").querySelector(".hlist");
140
+ if (!old) return;
141
+ const temp = document.createElement("div");
142
+ temp.innerHTML = String(list());
143
+ const nav = temp.querySelector(".hlist");
144
+ const top = old.scrollTop;
145
+ old.replaceWith(nav);
146
+ nav.scrollTop = top;
147
+ bindChatItems(nav);
148
+ }
149
+
150
+ const sendButton = () => sending || remoteBusy
151
+ ? html`<button type="button" class="ib hgo stop" id="hstop" aria-label="Stop" title="Stop">${ico("x")}</button>`
152
+ : html`<button class="ib hgo" aria-label="Send" title="Send (Enter)">${ico("send")}</button>`;
153
+
154
+ function syncSendButton() {
155
+ const b = $("hbox")?.querySelector(".hgo");
156
+ if (b && b.classList.contains("stop") !== (sending || remoteBusy)) b.outerHTML = String(sendButton());
157
+ if ($("hstop")) $("hstop").onclick = () => post("/chat/stop", { id: cur && cur.id });
158
+ }
159
+
160
+ function newChat() {
161
+ if (sending) return;
162
+ clearTimeout(poll);
163
+ cur = null;
164
+ attachments = [];
165
+ remoteBusy = false;
166
+ remember(null);
167
+ if (phone()) side = false;
168
+ vt(draw).then(() => $("hq").focus());
169
+ }
170
+
171
+ function draw() {
172
+ const h = $("home");
173
+ // Full redraws keep the draft and caret; streamed replies update only the last message.
174
+ const typing = document.activeElement && document.activeElement.id === "hq" ? $("hq").selectionStart : -1;
175
+ const empty = !cur || !cur.messages.length;
176
+ // A redraw replaces the log: keep the reader where they were unless they were at the bottom.
177
+ const old = $("hlog");
178
+ if (shown !== (cur && cur.id)) following = true;
179
+ const top = old ? old.scrollTop : 0;
180
+ if (shown !== (cur && cur.id)) seen = 0;
181
+ if (side === null) side = sideAtStart();
182
+ 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>${empty ? "" : html`<span class="hwhere">${ico("board")}${cur.project ? name(cur.project) : "No project"}</span>`}</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="Message the agent" aria-label="Message the agent"></textarea></div>${sendButton()}</form>${empty ? chips() : ""}</div>`);
184
+ seen = empty ? 0 : cur.messages.length;
185
+ shown = cur && cur.id;
186
+ $("htog").onclick = () => setSide(!side);
187
+ $("hclose").onclick = () => setSide(false);
188
+ $("hscrim").onclick = () => setSide(false);
189
+ const q = $("hq");
190
+ renderAttachments();
191
+ $("hattach").disabled = sending;
192
+ $("hattach").onclick = () => $("hfile").click();
193
+ $("hfile").onchange = (e) => { addFiles([...e.target.files]); e.target.value = ""; };
194
+ q.onpaste = (e) => {
195
+ const files = [...e.clipboardData.items].filter((it) => it.kind === "file").map((it) => it.getAsFile()).filter(Boolean);
196
+ if (files.length) { e.preventDefault(); addFiles(files.map((f) => f.name === "image.png" ? new File([f], `paste-${Date.now()}.png`, { type: f.type }) : f)); }
197
+ };
198
+ $("hbox").ondragover = (e) => { if (Array.from(e.dataTransfer?.types || []).includes("Files")) e.preventDefault(); };
199
+ $("hbox").ondrop = (e) => { if (e.dataTransfer.files.length) { e.preventDefault(); addFiles([...e.dataTransfer.files]); } };
200
+ draft(q, "home:" + (cur ? cur.id : "new"));
201
+ grow(q);
202
+ q.oninput = () => grow(q);
203
+ q.onkeydown = (e) => {
204
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing) {
205
+ e.preventDefault();
206
+ $("hbox").requestSubmit();
207
+ }
208
+ };
209
+ $("hbox").onsubmit = (e) => {
210
+ e.preventDefault();
211
+ send(q.value);
212
+ };
213
+ syncSendButton();
214
+ $("hnewtop").onclick = newChat;
215
+ $("hnewtop").disabled = sending;
216
+ bindChatItems(h);
217
+ h.querySelectorAll("[data-s]").forEach(
218
+ (b) =>
219
+ (b.onclick = () => {
220
+ q.value = b.dataset.s;
221
+ q.focus();
222
+ grow(q);
223
+ if (!b.dataset.s.endsWith(" ")) $("hbox").requestSubmit();
224
+ }),
225
+ );
226
+ if (typing >= 0) {
227
+ q.focus();
228
+ q.setSelectionRange(typing, typing);
229
+ }
230
+ // The agent links files by their path on disk, which the board cannot serve: the text stays, the path is its tooltip.
231
+ bindReply(h);
232
+ const log = $("hlog");
233
+ log.onwheel = (e) => { if (e.deltaY < 0 && log.scrollHeight > log.clientHeight) following = false; };
234
+ log.onscroll = () => { following = log.scrollHeight - log.scrollTop - log.clientHeight <= 0.5; };
235
+ if (following) log.scrollTop = log.scrollHeight;
236
+ else log.scrollTop = top;
237
+ }
238
+
239
+ function grow(t) {
240
+ t.style.height = "auto";
241
+ t.style.height = Math.min(t.scrollHeight, 220) + "px";
242
+ }
243
+
244
+ function renderAttachments() {
245
+ const box = $("hatt");
246
+ if (!box) return;
247
+ box.innerHTML = String(html`${attachments.map((f, i) => html`<span>${ico("clip")}${f.name}<button type="button" data-file="${i}" aria-label="Remove ${f.name}">×</button></span>`)}`);
248
+ box.querySelectorAll("[data-file]").forEach((b) => b.onclick = () => { attachments.splice(Number(b.dataset.file), 1); renderAttachments(); });
249
+ }
250
+
251
+ function addFiles(files) {
252
+ if (sending) { toast("Wait for the current reply"); return; }
253
+ for (const file of files) {
254
+ if (attachments.length >= 5 || file.size > 10 * 1024 * 1024 || attachments.reduce((n, f) => n + f.size, 0) + file.size > 20 * 1024 * 1024) { toast("Up to 5 files, 10 MB each and 20 MB total"); break; }
255
+ attachments.push(file);
256
+ }
257
+ renderAttachments();
258
+ }
259
+
260
+ async function refreshChats() {
261
+ try {
262
+ chats = (await get("/chats")).chats || [];
263
+ } catch (e) {
264
+ chats = [];
265
+ }
266
+ }
267
+
268
+ async function refresh() {
269
+ await refreshChats();
270
+ draw();
271
+ }
272
+
273
+ async function show(id) {
274
+ const c = await get("/chat?id=" + encodeURIComponent(id));
275
+ if (c.error) return toast(c.error);
276
+ if (cur?.id !== c.id) attachments = [];
277
+ const same = cur?.id === c.id && cur.messages.length === c.messages.length && !!$("hlog");
278
+ cur = c;
279
+ remoteBusy = !!c.busy;
280
+ remember(c.id);
281
+ if (same) { updateReply(c.messages.at(-1)); syncSendButton(); }
282
+ else draw();
283
+ follow(c.project);
284
+ // A turn started from another tab, or before a reload, is still running: follow it until it saves.
285
+ clearTimeout(poll);
286
+ if (c.busy && !sending) poll = setTimeout(() => cur && cur.id === id && show(id), 2000);
287
+ }
288
+
289
+ async function send(text) {
290
+ text = text.trim();
291
+ if ((!text && !attachments.length) || sending || remoteBusy) return;
292
+ const files = attachments;
293
+ attachments = [];
294
+ clearTimeout(poll);
295
+ const at = new Date().toISOString();
296
+ const was = cur ? cur.id : "new";
297
+ const fresh = !cur || !cur.messages.length;
298
+ cur = cur || { id: null, title: text || files[0].name, project: here(), messages: [] };
299
+ const reply = { role: "agent", text: "", steps: [], activity: "Thinking…", at };
300
+ cur.messages.push({ role: "user", text, files: files.map((f) => ({ name: f.name })), at }, reply);
301
+ sending = true;
302
+ try {
303
+ sessionStorage.removeItem(DK + "home:" + was);
304
+ if (fresh) sessionStorage.setItem("kz-chat-pending", at);
305
+ } catch (e) {}
306
+ // The first message: the box glides from the middle to the bottom.
307
+ following = true;
308
+ await (fresh ? vt(draw) : (draw(), undefined));
309
+ $("hlog").scrollTop = $("hlog").scrollHeight;
310
+ let accepted = false;
311
+ try {
312
+ const form = new FormData();
313
+ form.set("id", cur.id || ""); form.set("text", text); form.set("project", cur.project || "");
314
+ files.forEach((f) => form.append("files", f));
315
+ const r = files.length ? await fetch("/chat", { method: "POST", body: form }) : await post("/chat", { id: cur.id, text, project: cur.project });
316
+ if (!r.ok) {
317
+ reply.error = (await r.json()).error || "Could not send";
318
+ attachments = [...files, ...attachments]; renderAttachments();
319
+ return;
320
+ }
321
+ accepted = true;
322
+ const rd = r.body.getReader(),
323
+ dec = new TextDecoder();
324
+ let buf = "";
325
+ for (let x; !(x = await rd.read()).done; ) {
326
+ buf += dec.decode(x.value, { stream: true });
327
+ let i;
328
+ while ((i = buf.indexOf("\n")) >= 0) {
329
+ const line = buf.slice(0, i);
330
+ buf = buf.slice(i + 1);
331
+ let e;
332
+ try {
333
+ e = JSON.parse(line);
334
+ } catch (err) {
335
+ continue;
336
+ }
337
+ if (e.t === "chat") {
338
+ cur.id = shown = e.id;
339
+ remember(e.id);
340
+ try { sessionStorage.removeItem("kz-chat-pending"); } catch (err) {}
341
+ // In the list from its first message, marked busy, not only once the turn ends.
342
+ get("/chats").then((r) => {
343
+ chats = r.chats || chats;
344
+ drawList();
345
+ });
346
+ }
347
+ if (e.t === "text") reply.text += (reply.text ? "\n\n" : "") + e.text;
348
+ if (e.t === "status") reply.activity = e.text;
349
+ if (e.t === "step") { reply.steps.push(e.step); reply.activity = "Thinking…"; }
350
+ if (e.t === "error") reply.error = e.error;
351
+ if (e.t === "project") {
352
+ cur.project = e.dir;
353
+ follow(e.dir);
354
+ }
355
+ updateReply(reply);
356
+ }
357
+ }
358
+ } catch (e) {
359
+ reply.error = "Lost the connection; the agent keeps going and the chat saves when it finishes.";
360
+ if (!accepted) { attachments = [...files, ...attachments]; renderAttachments(); }
361
+ } finally {
362
+ try { sessionStorage.removeItem("kz-chat-pending"); } catch (e) {}
363
+ sending = false;
364
+ delete reply.activity;
365
+ if (accepted && cur?.id) {
366
+ try { await show(cur.id); }
367
+ catch { remoteBusy = false; updateReply(reply); }
368
+ } else { remoteBusy = false; updateReply(reply); }
369
+ syncSendButton();
370
+ $("hattach").disabled = false;
371
+ $("hnewtop").disabled = false;
372
+ await refreshChats();
373
+ drawList();
374
+ }
375
+ }
376
+
377
+ // The Home view opens: every chat, and the open one kept.
378
+ export async function openHome() {
379
+ await refreshChats();
380
+ let id;
381
+ try { id = sessionStorage.getItem("kz-chat"); } catch (e) {}
382
+ if (!id) {
383
+ try {
384
+ const pending = sessionStorage.getItem("kz-chat-pending");
385
+ if (pending) id = chats.find((c) => c.updated >= pending)?.id;
386
+ } catch (e) {}
387
+ }
388
+ if (id && chats.some((c) => c.id === id)) await show(id);
389
+ else { remember(null); draw(); }
390
+ }
391
+
392
+ // A project picked above: a new chat's greeting names it. Only then: a redraw replays the greeting's entrance.
393
+ let greeted;
394
+ addEventListener("kz-state", () => {
395
+ const d = here();
396
+ if (d === greeted) return;
397
+ greeted = d;
398
+ if (document.body.classList.contains("homev") && !sending && (!cur || !cur.messages.length)) draw();
399
+ });
package/web/board/live.ts CHANGED
@@ -8,16 +8,20 @@ import { go, markView } from "./views.ts";
8
8
 
9
9
  // ---- live
10
10
  let boot = null;
11
+ let pendingReload = false;
12
+ function reloadWhenAway() {
13
+ if (document.body.classList.contains("homev")) pendingReload = true;
14
+ else location.reload();
15
+ }
11
16
  function listen() {
12
17
  const es = new EventSource("/events");
13
18
  es.onmessage = (ev) => {
14
19
  if (ev.data === "changed") {
15
20
  load(true);
16
21
  if (srcOpen() && !iceBusy && !$("src-go")?.disabled && !$("src-add")?.disabled) openSources();
17
- } else if (ev.data === "reload") location.reload();
18
- else if (ev.data.startsWith("hello ")) {
22
+ } else if (ev.data.startsWith("hello ")) {
19
23
  const b = ev.data.slice(6);
20
- if (boot && b !== boot) location.reload();
24
+ if (boot && b !== boot) reloadWhenAway();
21
25
  boot = b;
22
26
  }
23
27
  };
@@ -32,12 +36,16 @@ function listen() {
32
36
  const v0 = ((v) => (v === "icebox" ? "sources" : v))(new URLSearchParams(location.search).get("view"));
33
37
 
34
38
  export function initLive() {
39
+ addEventListener("kz-view", () => { if (pendingReload && !document.body.classList.contains("homev")) location.reload(); });
35
40
  // Back from a terminal: what was committed or pushed there touched nothing the server watches.
36
41
  addEventListener("focus", () => load(true));
37
- markView(["settings", "sources", "terminal"].includes(v0) ? v0 : "board");
38
- document.body.classList.toggle("paged", ["settings", "sources", "terminal"].includes(v0));
42
+ // No view in the address is Home.
43
+ const first = ["settings", "sources", "terminal", "board"].includes(v0) ? v0 : "home";
44
+ markView(first);
45
+ document.body.classList.toggle("paged", first !== "board");
39
46
  document.body.classList.toggle("ice", v0 === "sources");
40
47
  document.body.classList.toggle("termv", v0 === "terminal");
48
+ document.body.classList.toggle("homev", first === "home");
41
49
  (async () => {
42
50
  let d;
43
51
  try {
@@ -49,7 +49,7 @@ function pop(on) {
49
49
  $("projq").focus();
50
50
  }
51
51
  }
52
- async function pick(v) {
52
+ export async function pick(v) {
53
53
  if (v === "__find") {
54
54
  toast("Searching…");
55
55
  const j = await post("/find", {});
@@ -4,9 +4,12 @@ import { openSources } from "./icebox.ts";
4
4
  import { close } from "./panel.ts";
5
5
  import { openSettings } from "./settings.ts";
6
6
  import { openTerms, termsStop } from "./terms.ts";
7
+ import { openHome } from "./home.ts";
7
8
 
8
- // ---- views: the board, Settings and the Icebox as pages in the docked panel, or the Terminal page; each with its own address
9
+ // ---- views: Home (the chat, at /), the board, Settings and the Icebox as pages in the docked panel, or the Terminal page; each with its own address
9
10
  export let view = "board";
11
+ // The board's own area, not the docked panel.
12
+ const AREA = ["board", "terminal", "home"];
10
13
  export const markView = (v) => {
11
14
  document
12
15
  .querySelectorAll(".rail a.it")
@@ -14,27 +17,30 @@ export const markView = (v) => {
14
17
  a.dataset.view === v ? a.setAttribute("aria-current", "page") : a.removeAttribute("aria-current"),
15
18
  );
16
19
  // The Icebox is titled in the header, top left, like the board.
17
- document.querySelector(".hdr h1").textContent = v === "sources" ? "Icebox" : v === "terminal" ? "Terminal" : "Board";
20
+ document.querySelector(".hdr h1").textContent = v === "sources" ? "Icebox" : v === "terminal" ? "Terminal" : v === "home" ? "Home" : "Board";
18
21
  };
19
22
  export function go(v, push) {
20
23
  store.pageGen++;
21
24
  if (v === "icebox") v = "sources";
22
- if (!["settings", "sources", "terminal"].includes(v)) v = "board";
25
+ if (!["settings", "sources", "terminal", "board"].includes(v)) v = "home";
23
26
  const was = view;
24
27
  view = v;
25
28
  markView(v);
26
29
  document.body.classList.toggle("paged", v !== "board");
27
30
  document.body.classList.toggle("ice", v === "sources");
28
31
  document.body.classList.toggle("termv", v === "terminal");
32
+ document.body.classList.toggle("homev", v === "home");
29
33
  if (push && v !== was)
30
- history.pushState(null, "", v === "board" ? location.pathname : "?view=" + (v === "sources" ? "icebox" : v));
34
+ history.pushState(null, "", v === "home" ? location.pathname : "?view=" + (v === "sources" ? "icebox" : v));
35
+ dispatchEvent(new Event("kz-view"));
31
36
  const p = $("panel");
32
37
  if (v === "terminal") openTerms();
33
38
  else termsStop();
39
+ if (v === "home") openHome();
34
40
  // The Terminal page is the board's own area, not the docked panel: the panel closes as on the board.
35
- if (v === "board" || v === "terminal") {
36
- if (was === "board" || was === "terminal") {
37
- if (v === "terminal" && was === "board") {
41
+ if (AREA.includes(v)) {
42
+ if (AREA.includes(was)) {
43
+ if (v !== "board" && was === "board") {
38
44
  view = "board";
39
45
  close();
40
46
  view = v;
@@ -69,7 +75,7 @@ export function initViews() {
69
75
  document.querySelector(".rail .home").onclick = (e) => {
70
76
  if (e.ctrlKey || e.metaKey || e.shiftKey || e.button) return;
71
77
  e.preventDefault();
72
- vt(() => go("board", true));
78
+ vt(() => go("home", true));
73
79
  };
74
80
  addEventListener("popstate", () => vt(() => go(new URLSearchParams(location.search).get("view"))));
75
81
  // The menu's theme switch while Settings shows: its Theme row follows.