kaizen-agent 1.79.0 → 1.80.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) 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 +180 -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 +4 -2
  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 +672 -0
  36. package/web/board/task-results.ts +235 -0
  37. package/web/board/tasks.ts +214 -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 +24 -2
  42. package/web/board.html +62 -35
  43. package/web/board.js +403 -142
  44. package/web/notebook.js +388 -153
  45. package/web/notes.html +21 -11
  46. package/web/term.js +1 -1
  47. package/web/video.html +27 -11
  48. package/web/video.js +415 -180
  49. package/web/video.ts +5 -5
  50. package/web/board/new-agent.ts +0 -20
@@ -0,0 +1,672 @@
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, modal, dataUrls, type Safe } from "./dom.ts";
4
+ import { store } from "./store.ts";
5
+ import { toast } from "./toast.ts";
6
+ import { attentionTasks, setTaskAttention } from "./badge.ts";
7
+ import { resultView, loadTextArtifacts, loadLiveArtifacts, type TaskResult } from "./task-results.ts";
8
+
9
+ export type TaskAttention = { category: "needs-you" | "in-progress" | "completed"; reason: string; action: string };
10
+ export type TaskDecision = {
11
+ id: string;
12
+ kind: "question" | "proposal" | "project" | string;
13
+ text: string;
14
+ summary?: string;
15
+ details?: string;
16
+ options?: string[];
17
+ };
18
+ export type TaskView = {
19
+ id: string;
20
+ dir: string;
21
+ title: string;
22
+ goal: string;
23
+ revision: number;
24
+ updatedAt?: number | string;
25
+ status?: string;
26
+ attention: TaskAttention;
27
+ decision?: TaskDecision | null;
28
+ messages?: { id: string; role: string; text: string; at?: number | string }[];
29
+ inputs?: { id: string; text: string; state: string; at?: number | string }[];
30
+ activeRun?: string | null;
31
+ runs?: (string | { id: string })[];
32
+ acceptedResultId?: string | null;
33
+ currentResultId?: string | null;
34
+ files?: { name: string; url?: string }[];
35
+ legacy?: { kind: string; id?: string; text?: string; state?: string };
36
+ error?: string;
37
+ projectName?: string;
38
+ };
39
+ export type TaskPageData = {
40
+ task: TaskView;
41
+ results?: TaskResult[];
42
+ projects?: { dir: string; name?: string; label?: string }[];
43
+ defaults?: { agent?: string; workflow?: string; permissions?: string };
44
+ };
45
+ const queued = (t: TaskView) => (t.inputs ?? []).filter((i) => ["received", "queued", "dispatched"].includes(i.state));
46
+ export function canAcceptTask(t: TaskView, result?: TaskResult) {
47
+ return (
48
+ !!result &&
49
+ result.id === t.currentResultId &&
50
+ !t.decision &&
51
+ !t.activeRun &&
52
+ !queued(t).length &&
53
+ t.attention.category !== "completed"
54
+ );
55
+ }
56
+ export const taskHref = (t: Pick<TaskView, "id" | "dir">) =>
57
+ `?view=task&task=${encodeURIComponent(t.id)}&dir=${encodeURIComponent(t.dir || "")}`;
58
+ export const taskStatus = (t: TaskView) => t.attention?.reason || t.status || "Saved";
59
+ const readDraft = (key: string) => {
60
+ try {
61
+ return sessionStorage.getItem("kz-task:" + key) || "";
62
+ } catch {
63
+ return "";
64
+ }
65
+ };
66
+ const saveDraft = (key: string, text: string) => {
67
+ try {
68
+ sessionStorage.setItem("kz-task:" + key, text);
69
+ } catch {}
70
+ };
71
+ const operationId = () => crypto.randomUUID();
72
+ let go: (view: string, push?: boolean) => void = () => {};
73
+ let followCurrent = true;
74
+ let data: TaskPageData | null = null,
75
+ generation = 0,
76
+ selectedResult = "",
77
+ selectedArtifact = "",
78
+ signature = "",
79
+ pending = false;
80
+ let currentId = "",
81
+ currentDir = "";
82
+ let timer: ReturnType<typeof setTimeout> | undefined;
83
+ const projectName = (t: TaskView) =>
84
+ t.projectName ||
85
+ data?.projects?.find((p) => p.dir === t.dir)?.name ||
86
+ data?.projects?.find((p) => p.dir === t.dir)?.label ||
87
+ (t.dir
88
+ ? t.dir
89
+ .replace(/[\\/]\.kaizen$/, "")
90
+ .split(/[\\/]/)
91
+ .pop()
92
+ : "Choose a project");
93
+
94
+ export async function taskRequest(body: Record<string, unknown>) {
95
+ try {
96
+ const r = await fetch("/task", {
97
+ method: "POST",
98
+ headers: { "content-type": "application/json" },
99
+ body: JSON.stringify(body),
100
+ });
101
+ const value = await r.json();
102
+ if (!r.ok || value.ok === false) {
103
+ toast(value.why || value.error || "That did not work. Your message is still saved here.");
104
+ return { ...value, ok: false, conflict: r.status === 409 };
105
+ }
106
+ return { ...value, ok: true };
107
+ } catch {
108
+ toast("The server could not be reached. Your draft is still here; try again.");
109
+ return { ok: false };
110
+ }
111
+ }
112
+ export function navigateTask(t: Pick<TaskView, "id" | "dir">, replace = false) {
113
+ (replace ? history.replaceState : history.pushState).call(history, null, "", taskHref(t));
114
+ go("task");
115
+ }
116
+ export async function openTaskRecord(t: TaskView) {
117
+ if (t.legacy) {
118
+ const r = await taskRequest({ op: "adopt", dir: t.dir, legacy: t.legacy, operationId: operationId() });
119
+ if (r.ok && r.task) return navigateTask(r.task);
120
+ return;
121
+ }
122
+ navigateTask(t);
123
+ }
124
+ function decisionView(t: TaskView): Safe | string {
125
+ const d = t.decision;
126
+ if (!d || d.kind === "project") return "";
127
+ return html`<section class="tp-decision" aria-labelledby="tp-decision-title">
128
+ <h3 id="tp-decision-title">
129
+ ${d.kind === "proposal" ? "Confirm the proposal" : d.kind === "project" ? "Choose a project" : "Your answer is needed"}
130
+ </h3>
131
+ <p>${d.summary || d.text}</p>
132
+ ${d.summary && d.text !== d.summary ? html`<p>${d.text}</p>` : ""}${
133
+ d.details
134
+ ? html`<details>
135
+ <summary>Detailed plan</summary>
136
+ <pre class="tp-text">${d.details}</pre>
137
+ </details>`
138
+ : ""
139
+ }${
140
+ d.kind === "proposal"
141
+ ? html`<button
142
+ type="button"
143
+ class="btn pri"
144
+ id="tp-confirm"
145
+ data-decision-id="${d.id}"
146
+ ${pending ? html` disabled` : ""}
147
+ >
148
+ Confirm proposal
149
+ </button>
150
+ <p class="dim">Production starts after you confirm this version. Ask for changes below if needed.</p>`
151
+ : d.options?.length
152
+ ? html`<div class="tp-options">
153
+ ${d.options.map((o) => html`<button class="btn" type="button" data-answer="${o}">${o}</button>`)}
154
+ </div>`
155
+ : ""
156
+ }
157
+ </section>`;
158
+ }
159
+ function projectView(t: TaskView): Safe | string {
160
+ if (t.dir && t.decision?.kind !== "project") return "";
161
+ return html`<section class="tp-decision">
162
+ <h3>Where should this task belong?</h3>
163
+ <p>Your goal and files are saved. Choose a named project or create one.</p>
164
+ <label for="tp-project">Project</label
165
+ ><select id="tp-project" class="sel">
166
+ <option value="">Choose a project</option>
167
+ ${(data?.projects ?? []).map(
168
+ (p) =>
169
+ html`<option value="${p.dir}">
170
+ ${(p.name || p.label || p.dir)
171
+ .replace(/[\\/]\.kaizen$/, "")
172
+ .split(/[\\/]/)
173
+ .pop()}
174
+ </option>`,
175
+ )}</select
176
+ ><button type="button" class="btn" id="tp-select-project">Use project</button>
177
+ <form id="tp-project-form">
178
+ <label for="tp-project-name">New project name</label>
179
+ <div class="tp-inline">
180
+ <input id="tp-project-name" class="sel" required placeholder="Community workshop" /><button
181
+ type="submit"
182
+ class="btn"
183
+ >
184
+ Create project
185
+ </button>
186
+ </div>
187
+ </form>
188
+ </section>`;
189
+ }
190
+ function conversationView(t: TaskView): Safe {
191
+ return html`${projectView(t)}${decisionView(t)}
192
+ ${
193
+ t.files?.length
194
+ ? html`<details class="tp-references">
195
+ <summary>Reference files · ${t.files.length}</summary>
196
+ <ul>
197
+ ${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>`)}
198
+ </ul>
199
+ </details>`
200
+ : ""
201
+ }
202
+ <div class="tp-messages" role="log" aria-label="Task conversation" aria-live="polite" aria-relevant="additions">
203
+ ${(t.messages ?? []).map(
204
+ (m) =>
205
+ html`<article class="tp-message ${m.role === "user" ? "from-user" : "from-agent"}">
206
+ <div>
207
+ <strong>${m.role === "user" ? "You" : m.role === "system" ? "kaizen" : "Assistant"}</strong
208
+ >${m.at ? html`<time>${new Date(m.at).toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" })}</time>` : ""}
209
+ </div>
210
+ <p>${m.text}</p>
211
+ </article>`,
212
+ )}
213
+ </div>
214
+ ${
215
+ queued(t).length
216
+ ? html`<section class="tp-queue" aria-label="Requests awaiting completion">
217
+ <h3>Requests</h3>
218
+ ${queued(t).map(
219
+ (i) =>
220
+ html`<div>
221
+ <span class="tp-receipt"
222
+ >${i.state === "dispatched" ? "Processing" : i.state === "received" ? "Received" : "Queued for next pass"}</span
223
+ >
224
+ <p>${i.text}</p>
225
+ <small>Receipt ${i.id.slice(0, 8)}</small>
226
+ </div>`,
227
+ )}
228
+ </section>`
229
+ : ""
230
+ }`;
231
+ }
232
+ function technicalView(t: TaskView): 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`<details class="tp-technical" id="tp-technical-details">
240
+ <summary>Technical details</summary>
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
+ </details>`;
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
+ function draw() {
289
+ if (!data || !document.body.classList.contains("taskpagev")) return;
290
+ const t = data.task,
291
+ box = $("taskpagev");
292
+ if (!box.querySelector("#tp-composer")) {
293
+ box.innerHTML = String(
294
+ html`<header class="tp-head">
295
+ <a class="btn ghost" href="?view=tasks" id="tp-back">← Tasks</a>
296
+ <div>
297
+ <h1 id="tp-title"></h1>
298
+ <p id="tp-project-label"></p>
299
+ </div>
300
+ <button class="btn" type="button" id="tp-stop" hidden>Stop</button
301
+ ><button class="btn" type="button" id="tp-resume" hidden>Resume</button
302
+ ><button class="btn pri" type="button" id="tp-start" hidden>Start planning</button>
303
+ </header>
304
+ <div class="tp-status" role="status"><span id="tp-status"></span><span id="tp-next"></span></div>
305
+ <div class="tp-layout">
306
+ <section class="tp-results" aria-label="Task results">
307
+ <div id="tp-history"></div>
308
+ <div id="tp-result"></div>
309
+ <button type="button" class="btn pri" id="tp-accept" hidden>Looks good</button>
310
+ <div id="tp-accepted"></div>
311
+ <div id="tp-technical"></div>
312
+ </section>
313
+ <section class="tp-conversation" aria-label="Conversation and requests">
314
+ <h2>Conversation</h2>
315
+ <div id="tp-thread"></div>
316
+ <form id="tp-composer">
317
+ <label for="tp-message">Your message</label
318
+ ><textarea
319
+ id="tp-message"
320
+ placeholder="Ask a question or describe what you would like changed"
321
+ rows="4"
322
+ ></textarea>
323
+ <p id="tp-composer-help" class="dim"></p>
324
+ <div class="tp-compose-row">
325
+ <label for="tp-intent">Send as</label
326
+ ><select id="tp-intent" class="sel">
327
+ <option value="auto">Message</option>
328
+ <option value="change">Change request</option>
329
+ <option value="question">Question</option></select
330
+ ><button type="submit" class="btn pri" id="tp-submit">Send</button>
331
+ </div>
332
+ <p id="tp-receipt" role="status"></p>
333
+ </form>
334
+ </section>
335
+ </div>`,
336
+ );
337
+ $("tp-message").value = readDraft(t.id);
338
+ $("tp-message").oninput = () => saveDraft(t.id, $("tp-message").value);
339
+ $("tp-back").onclick = (e) => {
340
+ e.preventDefault();
341
+ go("tasks", true);
342
+ };
343
+ $("tp-composer").onsubmit = (e) => {
344
+ e.preventDefault();
345
+ void sendMessage();
346
+ };
347
+ $("tp-message").onkeydown = (e) => {
348
+ if ((e.metaKey || e.ctrlKey) && e.key === "Enter" && !e.isComposing) {
349
+ e.preventDefault();
350
+ void sendMessage();
351
+ }
352
+ };
353
+ $("tp-stop").onclick = () => void action("stop");
354
+ $("tp-resume").onclick = () => void action("resume");
355
+ $("tp-start").onclick = () => void action("start");
356
+ $("tp-accept").onclick = () => void action("accept", { resultId: data?.task.currentResultId });
357
+ }
358
+ $("tp-title").textContent = t.title;
359
+ $("tp-project-label").textContent = projectName(t);
360
+ $("tp-status").textContent = taskStatus(t);
361
+ $("tp-next").textContent = t.attention?.action || "";
362
+ $("tp-status").className = "tp-state " + (t.attention?.category ?? "");
363
+ document.title = t.title + " · kaizen";
364
+ const results = [...(data.results ?? [])].sort(
365
+ (a, b) => Number(new Date(a.createdAt ?? 0)) - Number(new Date(b.createdAt ?? 0)),
366
+ ),
367
+ selected =
368
+ results.find((r) => r.id === selectedResult) ??
369
+ results.find((r) => r.id === t.currentResultId) ??
370
+ results[results.length - 1];
371
+ if (followCurrent && t.currentResultId) selectedResult = t.currentResultId;
372
+ else selectedResult = selected?.id ?? "";
373
+ preservePatch(
374
+ "tp-history",
375
+ results.length
376
+ ? html`<label for="tp-version">Saved results</label
377
+ ><select class="sel" id="tp-version">
378
+ ${[...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>`)}
379
+ </select>
380
+ <p class="dim">Files are retained without automatic expiry. Live links remain mutable.</p>`
381
+ : "",
382
+ );
383
+ const resultMarkup = String(resultView(results.find((r) => r.id === selectedResult) ?? selected, selectedArtifact));
384
+ if (signature !== resultMarkup) {
385
+ if (preservePatch("tp-result", resultMarkup)) {
386
+ signature = resultMarkup;
387
+ void loadTextArtifacts($("tp-result"));
388
+ void loadLiveArtifacts($("tp-result"));
389
+ }
390
+ }
391
+ $("tp-version") &&
392
+ ($("tp-version").onchange = () => {
393
+ selectedResult = $("tp-version").value;
394
+ followCurrent = selectedResult === t.currentResultId;
395
+ selectedArtifact = "";
396
+ signature = "";
397
+ draw();
398
+ });
399
+ $("tp-result")
400
+ .querySelectorAll<HTMLElement>("[data-artifact]")
401
+ .forEach(
402
+ (b) =>
403
+ (b.onclick = () => {
404
+ selectedArtifact = b.dataset.artifact!;
405
+ b.blur();
406
+ signature = "";
407
+ draw();
408
+ $("tp-result")
409
+ .querySelector<HTMLElement>(`[data-artifact="${CSS.escape(selectedArtifact)}"]`)
410
+ ?.focus({ preventScroll: true });
411
+ }),
412
+ );
413
+ preservePatch("tp-thread", conversationView(t));
414
+ preservePatch("tp-technical", technicalView(t));
415
+ $("tp-accepted").textContent =
416
+ t.acceptedResultId && t.attention.category === "completed" ? "Accepted. Publishing is a separate action." : "";
417
+ $("tp-confirm") &&
418
+ ($("tp-confirm").onclick = () => void action("confirm", { decisionId: $("tp-confirm").dataset.decisionId }));
419
+ $("tp-select-project") &&
420
+ ($("tp-select-project").onclick = () => {
421
+ const projectDir = $("tp-project").value;
422
+ if (projectDir) void action("project", { projectDir });
423
+ else toast("Choose a named project first");
424
+ });
425
+ $("tp-project-form") &&
426
+ ($("tp-project-form").onsubmit = (e) => {
427
+ e.preventDefault();
428
+ const name = $("tp-project-name").value.trim();
429
+ if (name) void action("project", { name });
430
+ });
431
+ $("tp-thread")
432
+ .querySelectorAll<HTMLElement>("[data-answer]")
433
+ .forEach(
434
+ (b) =>
435
+ (b.onclick = () => {
436
+ $("tp-message").value = b.dataset.answer;
437
+ void sendMessage();
438
+ }),
439
+ );
440
+ updateActions();
441
+ }
442
+ async function action(op: string, extra: Record<string, unknown> = {}) {
443
+ if (pending || !data) return;
444
+ pending = true;
445
+ updateActions();
446
+ const request = {
447
+ op,
448
+ id: data.task.id,
449
+ dir: data.task.dir,
450
+ operationId: operationId(),
451
+ revision: data.task.revision,
452
+ ...extra,
453
+ };
454
+ const r = await taskRequest(request);
455
+ pending = false;
456
+ if (r.task && r.ok) {
457
+ if (r.task.dir !== currentDir || r.task.id !== currentId) return navigateTask(r.task, true);
458
+ data.task = r.task;
459
+ }
460
+ if (r.ok)
461
+ $("tp-receipt").textContent =
462
+ op === "stop"
463
+ ? "Cancellation requested. Waiting for confirmation; saved files are not rolled back."
464
+ : op === "accept"
465
+ ? "Result accepted. It has not been published by this action."
466
+ : op === "confirm"
467
+ ? "Proposal confirmed."
468
+ : "Saved.";
469
+ await refreshTask();
470
+ if (r.conflict)
471
+ $("tp-receipt").textContent =
472
+ "This task changed. Your message is still saved. Review the current result and send it again when ready.";
473
+ updateActions();
474
+ return r;
475
+ }
476
+ async function sendMessage() {
477
+ const input = $("tp-message"),
478
+ text = input?.value.trim();
479
+ if (!text || pending || !data) return;
480
+ const original = input.value;
481
+ const baseResultId = selectedResult || data.task.currentResultId || null;
482
+ const identity = JSON.stringify([text, baseResultId, data.task.decision?.id, $("tp-intent").value]);
483
+ let saved;
484
+ try {
485
+ saved = JSON.parse(readDraft(currentId + ":operation"));
486
+ } catch {}
487
+ const messageOperation = saved?.identity === identity ? saved.id : operationId();
488
+ saveDraft(currentId + ":operation", JSON.stringify({ identity, id: messageOperation }));
489
+ const r = await action("message", {
490
+ operationId: messageOperation,
491
+ text,
492
+ intent: $("tp-intent").value,
493
+ baseResultId,
494
+ decisionId: data.task.decision?.id,
495
+ });
496
+ if (r?.ok && input.value === original) {
497
+ followCurrent = true;
498
+ input.value = "";
499
+ saveDraft(currentId, "");
500
+ saveDraft(currentId + ":operation", "");
501
+ $("tp-receipt").textContent = "Message received. Follow its receipt in the conversation.";
502
+ }
503
+ input.focus();
504
+ }
505
+ export async function refreshTask() {
506
+ if (!currentId) return;
507
+ const id = currentId,
508
+ dir = currentDir,
509
+ gen = ++generation;
510
+ try {
511
+ const r = await fetch(`/task?id=${encodeURIComponent(id)}&dir=${encodeURIComponent(dir)}`),
512
+ next = await r.json();
513
+ if (gen !== generation || id !== currentId || !document.body.classList.contains("taskpagev")) return;
514
+ if (!r.ok || !next.task) {
515
+ if (!data)
516
+ $("taskpagev").innerHTML = String(
517
+ html`<div class="tk-empty">
518
+ <p>This task could not be opened</p>
519
+ <span>${next.why || next.error || "Refresh or return to Tasks."}</span
520
+ ><a class="btn" href="?view=tasks">Back to Tasks</a>
521
+ </div>`,
522
+ );
523
+ return;
524
+ }
525
+ if (data && next.task.revision < data.task.revision) return;
526
+ data = next;
527
+ if (attentionTasks)
528
+ setTaskAttention([...attentionTasks.filter((t) => t.id !== next.task.id || t.dir !== next.task.dir), next.task]);
529
+ draw();
530
+ } catch {
531
+ if (!data)
532
+ $("taskpagev").innerHTML =
533
+ '<div class="tk-empty"><p>The server could not be reached</p><a class="btn" href="?view=tasks">Back to Tasks</a></div>';
534
+ }
535
+ }
536
+ export function openTaskPage() {
537
+ const p = new URLSearchParams(location.search),
538
+ id = p.get("task") || "",
539
+ dir = p.get("dir") || "";
540
+ if (id !== currentId || dir !== currentDir) {
541
+ currentId = id;
542
+ currentDir = dir;
543
+ data = null;
544
+ followCurrent = true;
545
+ selectedResult = "";
546
+ selectedArtifact = "";
547
+ signature = "";
548
+ $("taskpagev").innerHTML = '<p class="tp-loading" role="status">Opening task…</p>';
549
+ }
550
+ void refreshTask();
551
+ clearTimeout(timer);
552
+ const poll = () => {
553
+ if (!document.body.classList.contains("taskpagev")) return;
554
+ void refreshTask();
555
+ timer = setTimeout(poll, 4000);
556
+ };
557
+ timer = setTimeout(poll, 4000);
558
+ }
559
+ export function newTaskDialog(dir?: string | null) {
560
+ const dl = modal(
561
+ html`<h2>What would you like to make?</h2>
562
+ <label for="task-goal">Describe your goal</label
563
+ ><textarea
564
+ id="task-goal"
565
+ rows="5"
566
+ placeholder="Make a registration website for our community workshop"
567
+ required
568
+ ></textarea>
569
+ <p class="dim">
570
+ Start with your goal. We will ask about the project and any missing details, then show a proposal to confirm.
571
+ </p>
572
+ <input type="file" id="task-files" multiple hidden />
573
+ <div class="att" id="task-picked"></div>
574
+ <details>
575
+ <summary>Project and technical details</summary>
576
+ <p>
577
+ ${dir ? "Use the current project. " : "Choose or create a named project after saving your goal. "}The
578
+ configured agent, workflow and tool permissions apply.
579
+ </p>
580
+ <p id="task-new-defaults" class="dim">Loading defaults…</p>
581
+ </details>
582
+ <p id="task-new-error" role="status"></p>
583
+ <div class="row">
584
+ <button type="button" class="btn" id="task-attach">Attach files</button
585
+ ><button type="button" class="btn ghost" id="task-cancel">Cancel</button
586
+ ><button type="submit" class="btn pri" id="task-start">Start</button>
587
+ </div>`,
588
+ );
589
+ const input = dl.querySelector<HTMLTextAreaElement>("#task-goal")!,
590
+ fileInput = dl.querySelector<HTMLInputElement>("#task-files")!,
591
+ files: File[] = [];
592
+ const op = operationId();
593
+ input.value = readDraft("new");
594
+ input.oninput = () => saveDraft("new", input.value);
595
+ const shown = () => (dl.querySelector("#task-picked")!.textContent = files.map((f) => f.name).join(" · "));
596
+ dl.querySelector<HTMLElement>("#task-attach")!.onclick = () => fileInput.click();
597
+ fileInput.onchange = () => {
598
+ files.push(...Array.from(fileInput.files ?? []));
599
+ fileInput.value = "";
600
+ shown();
601
+ };
602
+ input.onpaste = (e) => {
603
+ for (const it of Array.from(e.clipboardData?.items ?? []))
604
+ if (it.kind === "file") {
605
+ const f = it.getAsFile();
606
+ if (f) {
607
+ files.push(f);
608
+ e.preventDefault();
609
+ shown();
610
+ }
611
+ }
612
+ };
613
+ dl.querySelector<HTMLElement>("#task-cancel")!.onclick = () => dl.close();
614
+ dl.querySelector("form")!.onsubmit = async (e) => {
615
+ e.preventDefault();
616
+ const goal = input.value.trim();
617
+ if (!goal) return input.focus();
618
+ const button = dl.querySelector<HTMLButtonElement>("#task-start")!;
619
+ if (button.disabled) return;
620
+ button.disabled = true;
621
+ button.textContent = "Saving…";
622
+ const r = await taskRequest({
623
+ op: "create",
624
+ goal,
625
+ dir: dir ?? null,
626
+ files: await dataUrls(files),
627
+ operationId: op,
628
+ });
629
+ button.disabled = false;
630
+ button.textContent = "Start";
631
+ if (r.ok && r.task) {
632
+ saveDraft("new", "");
633
+ dl.close();
634
+ navigateTask(r.task);
635
+ } else
636
+ dl.querySelector("#task-new-error")!.textContent =
637
+ r.why || r.error || "Your goal is still here. Try saving again.";
638
+ };
639
+ void fetch("/tasks" + (dir ? "?dir=" + encodeURIComponent(dir) : ""))
640
+ .then((r) => r.json())
641
+ .then((r) => {
642
+ const d = r.defaults;
643
+ dl.querySelector("#task-new-defaults")!.textContent = d
644
+ ? [d.agent && "Agent: " + d.agent, d.workflow && "Workflow: " + d.workflow, d.permissions]
645
+ .filter(Boolean)
646
+ .join(" · ")
647
+ : "Project settings will be shown before work starts.";
648
+ })
649
+ .catch(() => {
650
+ dl.querySelector("#task-new-defaults")!.textContent =
651
+ "Defaults unavailable. The configured settings will be retained.";
652
+ });
653
+ input.focus();
654
+ }
655
+ export function initTaskPage(goTo: typeof go) {
656
+ go = goTo;
657
+ addEventListener("kz-state", () => {
658
+ if (document.body.classList.contains("taskpagev")) void refreshTask();
659
+ });
660
+ addEventListener("kz-view", () => {
661
+ generation++;
662
+ clearTimeout(timer);
663
+ });
664
+ addEventListener("kz-new-task", (e: CustomEvent) => {
665
+ e.preventDefault();
666
+ newTaskDialog(e.detail?.dir ?? (!store.all ? store.S.dir : null));
667
+ });
668
+ addEventListener("kz-open-task", (e: CustomEvent) => {
669
+ e.preventDefault();
670
+ navigateTask(e.detail);
671
+ });
672
+ }