kaizen-agent 1.79.1 → 1.81.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.
Files changed (51) hide show
  1. package/cli/hermes.ts +20 -0
  2. package/cli/install.ts +20 -1
  3. package/cli/localsend.ts +61 -4
  4. package/cli/report.ts +7 -4
  5. package/cli/settings.ts +2 -8
  6. package/cli/state.ts +19 -3
  7. package/cli/task-results.ts +133 -0
  8. package/cli/task-service.ts +179 -0
  9. package/cli/tasks.ts +201 -0
  10. package/cli/ui-audit.allow.json +6 -0
  11. package/cli/ui-audit.ts +427 -0
  12. package/cli/web.ts +72 -1
  13. package/cli/whatsapp.ts +112 -0
  14. package/package.json +2 -1
  15. package/skills/kaizen/SKILL.md +4 -0
  16. package/skills/kaizen/adapters.md +4 -0
  17. package/skills/kaizen/spec-build.md +5 -1
  18. package/skills/kaizen/spec-main.md +4 -0
  19. package/skills/kaizen/spec-plan.md +4 -0
  20. package/skills/kaizen/spec-review.md +4 -0
  21. package/skills/kaizen/spec.md +52 -0
  22. package/web/board/add-project.ts +1 -1
  23. package/web/board/badge.ts +70 -8
  24. package/web/board/cards.ts +12 -4
  25. package/web/board/dom.ts +10 -0
  26. package/web/board/icebox.ts +2 -2
  27. package/web/board/keys.ts +1 -1
  28. package/web/board/live.ts +9 -5
  29. package/web/board/phone.ts +4 -3
  30. package/web/board/rich.ts +4 -2
  31. package/web/board/run-view.ts +16 -14
  32. package/web/board/settings-automations.ts +2 -2
  33. package/web/board/settings-skills.ts +2 -2
  34. package/web/board/settings.ts +12 -14
  35. package/web/board/task-page.ts +590 -0
  36. package/web/board/task-results.ts +232 -0
  37. package/web/board/tasks.ts +216 -200
  38. package/web/board/terms.ts +17 -2
  39. package/web/board/views.ts +35 -9
  40. package/web/board/whatsapp-setup.ts +137 -0
  41. package/web/board/workspace.ts +25 -2
  42. package/web/board/zoom.ts +90 -0
  43. package/web/board.html +139 -40
  44. package/web/board.js +355 -141
  45. package/web/notebook.js +367 -153
  46. package/web/notes.html +16 -11
  47. package/web/term.js +1 -1
  48. package/web/video.html +22 -11
  49. package/web/video.js +401 -187
  50. package/web/video.ts +5 -5
  51. package/web/board/new-agent.ts +0 -20
@@ -0,0 +1,590 @@
1
+ // One durable task page across clarification, production, saved outputs and revisions.
2
+ // Polling patches the changing sections, leaving the composer and focused controls intact.
3
+ import { $, html, ico, modal, dataUrls, type Safe } from "./dom.ts";
4
+ import { store } from "./store.ts";
5
+ import { runPopup } from "./cards.ts";
6
+ import { toast } from "./toast.ts";
7
+ import { wireZoom } from "./zoom.ts";
8
+ import { attentionTasks, setTaskAttention } from "./badge.ts";
9
+ import { checksView, savedLine, resultView, loadTextArtifacts, loadLiveArtifacts, type TaskResult } from "./task-results.ts";
10
+
11
+ export type TaskAttention = { category: "needs-you" | "in-progress" | "completed"; reason: string; action: string };
12
+ export type TaskDecision = {
13
+ id: string;
14
+ kind: "question" | "proposal" | "project" | string;
15
+ text: string;
16
+ summary?: string;
17
+ details?: string;
18
+ options?: string[];
19
+ };
20
+ export type TaskView = {
21
+ id: string;
22
+ dir: string;
23
+ title: string;
24
+ goal: string;
25
+ revision: number;
26
+ updatedAt?: number | string;
27
+ status?: string;
28
+ attention: TaskAttention;
29
+ decision?: TaskDecision | null;
30
+ messages?: { id: string; role: string; text: string; at?: number | string }[];
31
+ inputs?: { id: string; text: string; state: string; at?: number | string }[];
32
+ activeRun?: string | null;
33
+ runs?: (string | { id: string })[];
34
+ acceptedResultId?: string | null;
35
+ currentResultId?: string | null;
36
+ files?: { name: string; url?: string }[];
37
+ legacy?: { kind: string; id?: string; text?: string; state?: string };
38
+ error?: string;
39
+ projectName?: string;
40
+ };
41
+ export type TaskPageData = {
42
+ task: TaskView;
43
+ results?: TaskResult[];
44
+ projects?: { dir: string; name?: string; label?: string }[];
45
+ defaults?: { agent?: string; workflow?: string; permissions?: string };
46
+ };
47
+ const queued = (t: TaskView) => (t.inputs ?? []).filter((i) => ["received", "queued", "dispatched"].includes(i.state));
48
+ export function canAcceptTask(t: TaskView, result?: TaskResult) {
49
+ return (
50
+ !!result &&
51
+ result.id === t.currentResultId &&
52
+ !t.decision &&
53
+ !t.activeRun &&
54
+ !queued(t).length &&
55
+ t.attention.category !== "completed"
56
+ );
57
+ }
58
+ export const taskHref = (t: Pick<TaskView, "id" | "dir">) =>
59
+ `?view=task&task=${encodeURIComponent(t.id)}&dir=${encodeURIComponent(t.dir || "")}`;
60
+ export const taskStatus = (t: TaskView) => t.attention?.reason || t.status || "Saved";
61
+ const readDraft = (key: string) => {
62
+ try {
63
+ return sessionStorage.getItem("kz-task:" + key) || "";
64
+ } catch {
65
+ return "";
66
+ }
67
+ };
68
+ const saveDraft = (key: string, text: string) => {
69
+ try {
70
+ sessionStorage.setItem("kz-task:" + key, text);
71
+ } catch {}
72
+ };
73
+ const operationId = () => crypto.randomUUID();
74
+ let go: (view: string, push?: boolean) => void = () => {};
75
+ let followCurrent = true;
76
+ let data: TaskPageData | null = null,
77
+ generation = 0,
78
+ selectedResult = "",
79
+ selectedArtifact = "",
80
+ signature = "",
81
+ pending = false;
82
+ let currentId = "",
83
+ currentDir = "";
84
+ let timer: ReturnType<typeof setTimeout> | undefined;
85
+ const projectName = (t: TaskView) =>
86
+ t.projectName ||
87
+ data?.projects?.find((p) => p.dir === t.dir)?.name ||
88
+ data?.projects?.find((p) => p.dir === t.dir)?.label ||
89
+ (t.dir
90
+ ? t.dir
91
+ .replace(/[\\/]\.kaizen$/, "")
92
+ .split(/[\\/]/)
93
+ .pop()
94
+ : "Choose a project");
95
+
96
+ export async function taskRequest(body: Record<string, unknown>) {
97
+ try {
98
+ const r = await fetch("/task", {
99
+ method: "POST",
100
+ headers: { "content-type": "application/json" },
101
+ body: JSON.stringify(body),
102
+ });
103
+ const value = await r.json();
104
+ if (!r.ok || value.ok === false) {
105
+ toast(value.why || value.error || "That did not work. Your message is still saved here.");
106
+ return { ...value, ok: false, conflict: r.status === 409 };
107
+ }
108
+ return { ...value, ok: true };
109
+ } catch {
110
+ toast("The server could not be reached. Your draft is still here; try again.");
111
+ return { ok: false };
112
+ }
113
+ }
114
+ export function navigateTask(t: Pick<TaskView, "id" | "dir">, replace = false) {
115
+ (replace ? history.replaceState : history.pushState).call(history, null, "", taskHref(t));
116
+ go("task");
117
+ }
118
+ export async function openTaskRecord(t: TaskView) {
119
+ if (t.legacy) {
120
+ const r = await taskRequest({ op: "adopt", dir: t.dir, legacy: t.legacy, operationId: operationId() });
121
+ if (r.ok && r.task) return navigateTask(r.task);
122
+ return;
123
+ }
124
+ navigateTask(t);
125
+ }
126
+ function decisionView(t: TaskView): Safe | string {
127
+ const d = t.decision;
128
+ if (!d || d.kind === "project") return "";
129
+ return html`<section class="tp-decision" aria-labelledby="tp-decision-title">
130
+ <h3 id="tp-decision-title">
131
+ ${d.kind === "proposal" ? "Confirm the proposal" : d.kind === "project" ? "Choose a project" : "Your answer is needed"}
132
+ </h3>
133
+ <p>${d.summary || d.text}</p>
134
+ ${d.summary && d.text !== d.summary ? html`<p>${d.text}</p>` : ""}${
135
+ d.details
136
+ ? html`<details>
137
+ <summary>Detailed plan</summary>
138
+ <pre class="tp-text">${d.details}</pre>
139
+ </details>`
140
+ : ""
141
+ }${
142
+ d.kind === "proposal"
143
+ ? html`<button
144
+ type="button"
145
+ class="btn pri"
146
+ id="tp-confirm"
147
+ data-decision-id="${d.id}"
148
+ ${pending ? html` disabled` : ""}
149
+ >
150
+ Confirm proposal
151
+ </button>
152
+ <p class="dim">Production starts after you confirm this version. Ask for changes below if needed.</p>`
153
+ : d.options?.length
154
+ ? html`<div class="tp-options">
155
+ ${d.options.map((o) => html`<button class="btn" type="button" data-answer="${o}">${o}</button>`)}
156
+ </div>`
157
+ : ""
158
+ }
159
+ </section>`;
160
+ }
161
+ function projectView(t: TaskView): Safe | string {
162
+ if (t.dir && t.decision?.kind !== "project") return "";
163
+ return html`<section class="tp-decision">
164
+ <h3>Where should this task belong?</h3>
165
+ <p>Your goal and files are saved. Choose a named project or create one.</p>
166
+ <label for="tp-project">Project</label
167
+ ><select id="tp-project" class="sel">
168
+ <option value="">Choose a project</option>
169
+ ${(data?.projects ?? []).map(
170
+ (p) =>
171
+ html`<option value="${p.dir}">
172
+ ${(p.name || p.label || p.dir)
173
+ .replace(/[\\/]\.kaizen$/, "")
174
+ .split(/[\\/]/)
175
+ .pop()}
176
+ </option>`,
177
+ )}</select
178
+ ><button type="button" class="btn" id="tp-select-project">Use project</button>
179
+ <form id="tp-project-form">
180
+ <label for="tp-project-name">New project name</label>
181
+ <div class="tp-inline">
182
+ <input id="tp-project-name" class="sel" required placeholder="Community workshop" /><button
183
+ type="submit"
184
+ class="btn"
185
+ >
186
+ Create project
187
+ </button>
188
+ </div>
189
+ </form>
190
+ </section>`;
191
+ }
192
+ function conversationView(t: TaskView): Safe {
193
+ return html`${projectView(t)}${decisionView(t)}
194
+ ${
195
+ t.files?.length
196
+ ? html`<details class="tp-references">
197
+ <summary>Reference files · ${t.files.length}</summary>
198
+ <ul>
199
+ ${t.files.map((f) => html`<li>${f.url && /^\/file\?/.test(f.url) ? html`<a href="${f.url}" target="_blank" rel="noopener noreferrer">${f.name}</a>` : f.name}</li>`)}
200
+ </ul>
201
+ </details>`
202
+ : ""
203
+ }
204
+ <div class="tp-messages" role="log" aria-label="Task conversation" aria-live="polite" aria-relevant="additions">
205
+ ${(t.messages ?? []).map((m) => {
206
+ const long = m.text.length > 320;
207
+ const body = long
208
+ ? html`<details class="tp-long"><summary>${m.text.slice(0, 280).trimEnd()}… <span>Show more</span></summary>${m.text}</details>`
209
+ : html`${m.text}`;
210
+ return html`<article class="tp-message ${m.role === "user" ? "from-user" : "from-agent"}">
211
+ <div>
212
+ <strong>${m.role === "user" ? "You" : m.role === "system" ? "kaizen" : "Assistant"}</strong
213
+ >${m.at ? html`<time>${new Date(m.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</time>` : ""}
214
+ </div>
215
+ <p>${body}</p>
216
+ </article>`;
217
+ })}
218
+ </div>
219
+ ${
220
+ queued(t).length
221
+ ? html`<div class="tp-queue" aria-label="Requests awaiting completion">
222
+ ${queued(t).map(
223
+ (i) =>
224
+ html`<span class="tp-receipt" title="Receipt ${i.id.slice(0, 8)}"
225
+ >${i.state === "dispatched" ? "Processing" : i.state === "received" ? "Received" : "Queued for next pass"}</span
226
+ >`,
227
+ )}
228
+ </div>`
229
+ : ""
230
+ }`;
231
+ }
232
+ function technicalView(t: TaskView, current?: TaskResult): Safe {
233
+ const runs = [
234
+ ...new Set([
235
+ ...(t.runs ?? []).map((r) => (typeof r === "string" ? r : r.id)),
236
+ ...(t.activeRun ? [t.activeRun] : []),
237
+ ]),
238
+ ];
239
+ return html`<div class="tp-technical" id="tp-technical-details">
240
+ ${checksView(current)}
241
+ <p>
242
+ ${data?.defaults?.agent ? "Agent: " + data.defaults.agent + ". " : "Configured project agent and workflow. "}${data?.defaults?.workflow ? "Workflow: " + data.defaults.workflow + ". " : ""}${data?.defaults?.permissions || "Tool permissions follow the existing project settings."}
243
+ </p>
244
+ <p class="dim">
245
+ Permission prompts may require the supported terminal controls in the workspace. Stop requests cancellation; it
246
+ does not undo files.
247
+ </p>
248
+ ${runs.length ? html`<nav aria-label="Linked runs">${runs.map((id) => html`<a class="btn" href="?view=run&id=${id}&dir=${encodeURIComponent(t.dir)}">Open workspace · ${id}</a>`)}</nav>` : html`<p>No run has started yet.</p>`}<small
249
+ >Task ${t.id} · revision ${t.revision}</small
250
+ >
251
+ </div>`;
252
+ }
253
+ function updateActions() {
254
+ if (!data) return;
255
+ const t = data.task,
256
+ current = (data.results ?? []).find((r) => r.id === t.currentResultId);
257
+ $("tp-accept").hidden = selectedResult !== t.currentResultId || !canAcceptTask(t, current);
258
+ $("tp-stop").hidden = !t.activeRun || ["interrupted", "failed", "stopped"].includes(t.status ?? "");
259
+ $("tp-stop").textContent = t.status === "stopping" ? "Stopping…" : "Stop";
260
+ $("tp-stop").disabled = pending || t.status === "stopping";
261
+ $("tp-resume").hidden = !["interrupted", "failed", "stopped"].includes(t.status ?? "");
262
+ $("tp-resume").textContent = t.status === "failed" ? "Retry" : "Resume";
263
+ $("tp-start").hidden =
264
+ !t.dir || !!t.activeRun || !!t.currentResultId || t.status !== "draft" || t.decision?.kind === "project";
265
+ $("tp-submit").disabled = pending;
266
+ $("tp-submit").textContent = pending ? "Sending…" : t.decision?.kind === "question" ? "Send answer" : "Send";
267
+ $("tp-composer-help").textContent = t.activeRun
268
+ ? "Changes are saved for the next safe pass. Questions do not interrupt production."
269
+ : t.attention.category === "completed"
270
+ ? "A new change stays in this task and starts a linked revision."
271
+ : "Ask a question or describe a change. Your message stays with this task.";
272
+ }
273
+ function preservePatch(id: string, markup: Safe | string) {
274
+ const box = $(id);
275
+ if (!box) return false;
276
+ const next = String(markup);
277
+ if (box.dataset.markup === next) return true;
278
+ // A focused decision/history control is not replaced by a background refresh.
279
+ if (box.contains(document.activeElement) && document.activeElement !== document.body) return false;
280
+ const opened = [...box.querySelectorAll<HTMLDetailsElement>("details")].map((d) => d.open);
281
+ box.innerHTML = next;
282
+ box.dataset.markup = next;
283
+ box.querySelectorAll<HTMLDetailsElement>("details").forEach((d, i) => {
284
+ if (opened[i] != null) d.open = opened[i];
285
+ });
286
+ return true;
287
+ }
288
+ // The conversation is a drawer: open by itself only while a decision waits for you, closed otherwise.
289
+ let drawer: boolean | null = null,
290
+ threadCount = -1;
291
+ const drawerOpen = () =>
292
+ drawer ?? !!data?.task.pendingDecision;
293
+ function applyDrawer() {
294
+ const on = drawerOpen();
295
+ $("tp-drawer").classList.toggle("on", on);
296
+ $("tp-chat").setAttribute("aria-expanded", String(on));
297
+ const t = data?.task;
298
+ $("tp-chat").querySelector<HTMLElement>(".tp-dot")!.hidden = on || !(t?.pendingDecision || t?.inputs?.some?.((i: any) => i.state === "queued"));
299
+ }
300
+ function draw() {
301
+ if (!data || !document.body.classList.contains("taskpagev")) return;
302
+ const t = data.task,
303
+ box = $("taskpagev");
304
+ if (!box.querySelector("#tp-composer")) {
305
+ box.innerHTML = String(
306
+ html`<header class="tp-head">
307
+ <a class="ib" href="?view=tasks" id="tp-back" aria-label="Back to tasks" title="Tasks">${ico("arrow")}</a>
308
+ <h1 id="tp-title"></h1>
309
+ <span id="tp-project-label" class="dim"></span>
310
+ <button class="btn" type="button" id="tp-stop" hidden>Stop</button
311
+ ><button class="btn" type="button" id="tp-resume" hidden>Resume</button
312
+ ><button class="btn pri" type="button" id="tp-start" hidden>Start planning</button
313
+ ><button type="button" class="btn pri" id="tp-accept" title="Accepting a result does not publish it. A preview alone does not prove that a backend works." hidden>Looks good</button
314
+ ><button type="button" class="ib" id="tp-chat" aria-label="Conversation" aria-expanded="false" title="Conversation">${ico("note")}<i class="tp-dot" hidden></i></button
315
+ ><details class="ice-filt" id="tp-info"><summary class="ib" aria-label="Task details" title="Details">${ico("more")}</summary><div class="ice-fpop tp-info-pop"><div id="tp-technical"></div></div></details>
316
+ </header>
317
+ <div class="tp-status" role="status"><span id="tp-status"></span><span id="tp-next"></span><span id="tp-saved" class="dim"></span></div>
318
+ <div class="tp-layout">
319
+ <section class="tp-results" aria-label="Task results">
320
+ <div id="tp-history"></div>
321
+ <div id="tp-result"></div>
322
+ <div id="tp-accepted"></div>
323
+ </section>
324
+ <div class="tp-conversation" id="tp-drawer" role="complementary" aria-label="Conversation and requests">
325
+ <header><h2>Conversation</h2><button type="button" class="ib" id="tp-drawer-x" aria-label="Close conversation">${ico("x")}</button></header>
326
+ <div id="tp-thread"></div>
327
+ </div>
328
+ </div>
329
+ <form id="tp-composer" class="tp-bar">
330
+ <div class="tp-compose">
331
+ <textarea id="tp-message" rows="1" aria-label="Your message" placeholder="Message the agent" title="Enter to send, Shift+Enter for a new line"></textarea>
332
+ <button type="submit" class="btn pri" id="tp-submit">Send</button>
333
+ </div>
334
+ <p id="tp-composer-help" class="dim" hidden></p>
335
+ <p id="tp-receipt" role="status"></p>
336
+ </form>
337
+ `,
338
+ );
339
+ $("tp-message").value = readDraft(t.id);
340
+ $("tp-message").oninput = () => saveDraft(t.id, $("tp-message").value);
341
+ $("tp-back").onclick = (e) => {
342
+ e.preventDefault();
343
+ go("tasks", true);
344
+ };
345
+ $("tp-composer").onsubmit = (e) => {
346
+ e.preventDefault();
347
+ void sendMessage();
348
+ };
349
+ $("tp-message").onkeydown = (e) => {
350
+ // Enter sends, Shift+Enter adds a line. A phone keyboard keeps Enter as a new line.
351
+ if (e.key === "Enter" && !e.shiftKey && !e.isComposing && !matchMedia("(pointer:coarse)").matches) {
352
+ e.preventDefault();
353
+ void sendMessage();
354
+ }
355
+ };
356
+ $("tp-chat").onclick = () => {
357
+ drawer = !drawerOpen();
358
+ applyDrawer();
359
+ };
360
+ $("tp-drawer-x").onclick = () => {
361
+ drawer = false;
362
+ applyDrawer();
363
+ };
364
+ $("tp-stop").onclick = () => void action("stop");
365
+ $("tp-resume").onclick = () => void action("resume");
366
+ $("tp-start").onclick = () => runPopup({ _k: "task:" + t.id, kind: "task", state: t.dir, text: t.title }, (pick) => void action("start", { pick }));
367
+ $("tp-accept").onclick = () => void action("accept", { resultId: data?.task.currentResultId });
368
+ }
369
+ $("tp-title").textContent = t.title;
370
+ $("tp-project-label").textContent = projectName(t);
371
+ $("tp-status").textContent = taskStatus(t);
372
+ $("tp-next").textContent = t.attention?.action || "";
373
+ $("tp-status").className = "tp-state " + (t.attention?.category ?? "");
374
+ document.title = t.title + " · kaizen";
375
+ const results = [...(data.results ?? [])].sort(
376
+ (a, b) => Number(new Date(a.createdAt ?? 0)) - Number(new Date(b.createdAt ?? 0)),
377
+ ),
378
+ selected =
379
+ results.find((r) => r.id === selectedResult) ??
380
+ results.find((r) => r.id === t.currentResultId) ??
381
+ results[results.length - 1];
382
+ if (followCurrent && t.currentResultId) selectedResult = t.currentResultId;
383
+ else selectedResult = selected?.id ?? "";
384
+ preservePatch(
385
+ "tp-history",
386
+ results.length > 1
387
+ ? html`<select class="sel" id="tp-version" aria-label="Saved results" title="Files are retained without automatic expiry. Live links remain mutable.">
388
+ ${[...results].reverse().map((r, i) => html`<option value="${r.id}" ${r.id === selectedResult ? html` selected` : ""}>${r.title || "Version " + (results.length - i)}${r.id === t.currentResultId ? " · current" : " · earlier saved output"}</option>`)}
389
+ </select>`
390
+ : "",
391
+ );
392
+ $("tp-saved").textContent = savedLine(results.find((r) => r.id === selectedResult) ?? selected);
393
+ const resultMarkup = String(resultView(results.find((r) => r.id === selectedResult) ?? selected, selectedArtifact));
394
+ if (signature !== resultMarkup) {
395
+ if (preservePatch("tp-result", resultMarkup)) {
396
+ signature = resultMarkup;
397
+ void loadTextArtifacts($("tp-result"));
398
+ void loadLiveArtifacts($("tp-result"));
399
+ }
400
+ }
401
+ $("tp-version") &&
402
+ ($("tp-version").onchange = () => {
403
+ selectedResult = $("tp-version").value;
404
+ followCurrent = selectedResult === t.currentResultId;
405
+ selectedArtifact = "";
406
+ signature = "";
407
+ draw();
408
+ });
409
+ $("tp-result")
410
+ .querySelectorAll<HTMLElement>("[data-artifact]")
411
+ .forEach(
412
+ (b) =>
413
+ (b.onclick = () => {
414
+ selectedArtifact = b.dataset.artifact!;
415
+ b.blur();
416
+ signature = "";
417
+ draw();
418
+ $("tp-result")
419
+ .querySelector<HTMLElement>(`[data-artifact="${CSS.escape(selectedArtifact)}"]`)
420
+ ?.focus({ preventScroll: true });
421
+ }),
422
+ );
423
+ wireZoom($("tp-result"));
424
+ const count = (t.messages ?? []).length;
425
+ const grew = preservePatch("tp-thread", conversationView(t)) && count !== threadCount;
426
+ threadCount = count;
427
+ if (grew) requestAnimationFrame(() => ($("tp-thread").scrollTop = $("tp-thread").scrollHeight));
428
+ applyDrawer();
429
+ preservePatch("tp-technical", technicalView(t, results.find((r) => r.id === selectedResult) ?? selected));
430
+ $("tp-accepted").textContent =
431
+ t.acceptedResultId && t.attention.category === "completed" ? "Accepted. Publishing is a separate action." : "";
432
+ $("tp-confirm") &&
433
+ ($("tp-confirm").onclick = () => void action("confirm", { decisionId: $("tp-confirm").dataset.decisionId }));
434
+ $("tp-select-project") &&
435
+ ($("tp-select-project").onclick = () => {
436
+ const projectDir = $("tp-project").value;
437
+ if (projectDir) void action("project", { projectDir });
438
+ else toast("Choose a named project first");
439
+ });
440
+ $("tp-project-form") &&
441
+ ($("tp-project-form").onsubmit = (e) => {
442
+ e.preventDefault();
443
+ const name = $("tp-project-name").value.trim();
444
+ if (name) void action("project", { name });
445
+ });
446
+ $("tp-thread")
447
+ .querySelectorAll<HTMLElement>("[data-answer]")
448
+ .forEach(
449
+ (b) =>
450
+ (b.onclick = () => {
451
+ $("tp-message").value = b.dataset.answer;
452
+ void sendMessage();
453
+ }),
454
+ );
455
+ updateActions();
456
+ }
457
+ async function action(op: string, extra: Record<string, unknown> = {}) {
458
+ if (pending || !data) return;
459
+ pending = true;
460
+ updateActions();
461
+ const request = {
462
+ op,
463
+ id: data.task.id,
464
+ dir: data.task.dir,
465
+ operationId: operationId(),
466
+ revision: data.task.revision,
467
+ ...extra,
468
+ };
469
+ const r = await taskRequest(request);
470
+ pending = false;
471
+ if (r.task && r.ok) {
472
+ if (r.task.dir !== currentDir || r.task.id !== currentId) return navigateTask(r.task, true);
473
+ data.task = r.task;
474
+ }
475
+ if (r.ok)
476
+ $("tp-receipt").textContent =
477
+ op === "stop"
478
+ ? "Cancellation requested. Waiting for confirmation; saved files are not rolled back."
479
+ : op === "accept"
480
+ ? "Result accepted. It has not been published by this action."
481
+ : op === "confirm"
482
+ ? "Proposal confirmed."
483
+ : "Saved.";
484
+ await refreshTask();
485
+ if (r.conflict)
486
+ $("tp-receipt").textContent =
487
+ "This task changed. Your message is still saved. Review the current result and send it again when ready.";
488
+ updateActions();
489
+ return r;
490
+ }
491
+ async function sendMessage() {
492
+ const input = $("tp-message"),
493
+ text = input?.value.trim();
494
+ if (!text || pending || !data) return;
495
+ const original = input.value;
496
+ const baseResultId = selectedResult || data.task.currentResultId || null;
497
+ const identity = JSON.stringify([text, baseResultId, data.task.decision?.id, "auto"]);
498
+ let saved;
499
+ try {
500
+ saved = JSON.parse(readDraft(currentId + ":operation"));
501
+ } catch {}
502
+ const messageOperation = saved?.identity === identity ? saved.id : operationId();
503
+ saveDraft(currentId + ":operation", JSON.stringify({ identity, id: messageOperation }));
504
+ const r = await action("message", {
505
+ operationId: messageOperation,
506
+ text,
507
+ intent: "auto",
508
+ baseResultId,
509
+ decisionId: data.task.decision?.id,
510
+ });
511
+ if (r?.ok && input.value === original) {
512
+ followCurrent = true;
513
+ input.value = "";
514
+ saveDraft(currentId, "");
515
+ saveDraft(currentId + ":operation", "");
516
+ $("tp-receipt").textContent = "Message received. Follow its receipt in the conversation.";
517
+ drawer = true;
518
+ applyDrawer();
519
+ }
520
+ input.focus();
521
+ }
522
+ export async function refreshTask() {
523
+ if (!currentId) return;
524
+ const id = currentId,
525
+ dir = currentDir,
526
+ gen = ++generation;
527
+ try {
528
+ const r = await fetch(`/task?id=${encodeURIComponent(id)}&dir=${encodeURIComponent(dir)}`),
529
+ next = await r.json();
530
+ if (gen !== generation || id !== currentId || !document.body.classList.contains("taskpagev")) return;
531
+ if (!r.ok || !next.task) {
532
+ if (!data)
533
+ $("taskpagev").innerHTML = String(
534
+ html`<div class="tk-empty">
535
+ <p>This task could not be opened</p>
536
+ <span>${next.why || next.error || "Refresh or return to Tasks."}</span
537
+ ><a class="btn" href="?view=tasks">Back to Tasks</a>
538
+ </div>`,
539
+ );
540
+ return;
541
+ }
542
+ if (data && next.task.revision < data.task.revision) return;
543
+ data = next;
544
+ if (attentionTasks)
545
+ setTaskAttention([...attentionTasks.filter((t) => t.id !== next.task.id || t.dir !== next.task.dir), next.task]);
546
+ draw();
547
+ } catch {
548
+ if (!data)
549
+ $("taskpagev").innerHTML =
550
+ '<div class="tk-empty"><p>The server could not be reached</p><a class="btn" href="?view=tasks">Back to Tasks</a></div>';
551
+ }
552
+ }
553
+ export function openTaskPage() {
554
+ const p = new URLSearchParams(location.search),
555
+ id = p.get("task") || "",
556
+ dir = p.get("dir") || "";
557
+ if (id !== currentId || dir !== currentDir) {
558
+ currentId = id;
559
+ currentDir = dir;
560
+ data = null;
561
+ followCurrent = true;
562
+ drawer = null;
563
+ selectedResult = "";
564
+ selectedArtifact = "";
565
+ signature = "";
566
+ $("taskpagev").innerHTML = '<p class="tp-loading" role="status">Opening task…</p>';
567
+ }
568
+ void refreshTask();
569
+ clearTimeout(timer);
570
+ const poll = () => {
571
+ if (!document.body.classList.contains("taskpagev")) return;
572
+ void refreshTask();
573
+ timer = setTimeout(poll, 4000);
574
+ };
575
+ timer = setTimeout(poll, 4000);
576
+ }
577
+ export function initTaskPage(goTo: typeof go) {
578
+ go = goTo;
579
+ addEventListener("kz-state", () => {
580
+ if (document.body.classList.contains("taskpagev")) void refreshTask();
581
+ });
582
+ addEventListener("kz-view", () => {
583
+ generation++;
584
+ clearTimeout(timer);
585
+ });
586
+ addEventListener("kz-open-task", (e: CustomEvent) => {
587
+ e.preventDefault();
588
+ navigateTask(e.detail);
589
+ });
590
+ }