@pat-lewczuk/cezar 0.1.0 → 0.1.2

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 (57) hide show
  1. package/dist/config.d.ts +62 -0
  2. package/dist/config.js +49 -0
  3. package/dist/config.js.map +1 -0
  4. package/dist/core/agent-runner.d.ts +13 -0
  5. package/dist/core/claude-cli-runner.js +23 -2
  6. package/dist/core/claude-cli-runner.js.map +1 -1
  7. package/dist/git-worktree.d.ts +56 -0
  8. package/dist/git-worktree.js +143 -0
  9. package/dist/git-worktree.js.map +1 -0
  10. package/dist/handoff.d.ts +42 -0
  11. package/dist/handoff.js +120 -0
  12. package/dist/handoff.js.map +1 -0
  13. package/dist/index.js +27 -6
  14. package/dist/index.js.map +1 -1
  15. package/dist/planner.d.ts +17 -0
  16. package/dist/planner.js +244 -0
  17. package/dist/planner.js.map +1 -0
  18. package/dist/runs/store.d.ts +40 -13
  19. package/dist/runs/store.js +33 -3
  20. package/dist/runs/store.js.map +1 -1
  21. package/dist/server/git.d.ts +5 -0
  22. package/dist/server/git.js +38 -0
  23. package/dist/server/git.js.map +1 -1
  24. package/dist/server/github.d.ts +29 -0
  25. package/dist/server/github.js +140 -0
  26. package/dist/server/github.js.map +1 -0
  27. package/dist/server/launch-key.d.ts +7 -0
  28. package/dist/server/launch-key.js +33 -0
  29. package/dist/server/launch-key.js.map +1 -0
  30. package/dist/server/pr.d.ts +22 -0
  31. package/dist/server/pr.js +98 -0
  32. package/dist/server/pr.js.map +1 -0
  33. package/dist/server/server.js +537 -19
  34. package/dist/server/server.js.map +1 -1
  35. package/dist/skills-remote.d.ts +35 -0
  36. package/dist/skills-remote.js +266 -0
  37. package/dist/skills-remote.js.map +1 -0
  38. package/dist/skills.d.ts +20 -6
  39. package/dist/skills.js +77 -12
  40. package/dist/skills.js.map +1 -1
  41. package/dist/todos.d.ts +60 -0
  42. package/dist/todos.js +166 -0
  43. package/dist/todos.js.map +1 -0
  44. package/dist/workflows/load.js +8 -10
  45. package/dist/workflows/load.js.map +1 -1
  46. package/dist/workflows/run.d.ts +62 -3
  47. package/dist/workflows/run.js +351 -45
  48. package/dist/workflows/run.js.map +1 -1
  49. package/dist/workflows/types.d.ts +96 -26
  50. package/dist/workflows/types.js +73 -2
  51. package/dist/workflows/types.js.map +1 -1
  52. package/package.json +1 -1
  53. package/scripts/mock-claude.mjs +118 -0
  54. package/web/app.js +2821 -154
  55. package/web/index.html +82 -23
  56. package/web/open-mercato.svg +11 -0
  57. package/web/style.css +1652 -222
package/web/app.js CHANGED
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
- /* cez cockpit — vanilla JS, no build step. Talks to the local server via
4
- fetch + Server-Sent Events. */
3
+ /* cez cockpit v2 — vanilla JS, no build step. Talks to the local server via
4
+ fetch + Server-Sent Events. Layout: a persistent sidebar (new task, nav,
5
+ run list, env footer) + one main view per tab. */
5
6
 
6
7
  const $ = (sel, el = document) => el.querySelector(sel);
7
8
 
@@ -12,8 +13,43 @@ const state = {
12
13
  lastSeq: 0, // dedup across SSE reconnect replays
13
14
  autoScroll: true,
14
15
  workflows: [],
16
+ taskSource: 'workflow', // 'workflow' (a chain) | 'skill' — what taskRef names
17
+ taskRef: null, // selected chain/skill name (the "≡ fix-and-verify" pill)
18
+ taskModel: '', // model override ('' = auto; the "⊞ auto" pill)
19
+ modelsAvailable: false, // claude CLI detected → model menu lists Claude models
20
+ srcMenuTab: 'workflow', // Workflows | Skills tab inside the source pill menu
21
+ srcMenuQuery: '', // search box inside the source pill menu
15
22
  pendingImages: [], // [{mediaType, data, preview}] queued for the next message
23
+ taskImages: [], // screenshots pasted into the new-task form
16
24
  listView: 'active', // 'active' | 'archived'
25
+ todos: [], // global inbox entries (spec 007)
26
+ plan: null, // {task, steps, rationale, fallback} — proposed chain (spec 008)
27
+ planDragIdx: null, // index of the plan step being dragged
28
+ variants: 1, // ×1/×2/×3 switch — parallel variants (spec 010)
29
+ expandedGroups: new Set(), // groupIds expanded in the run list
30
+ selectedGroupId: null, // group shown in the compare view (instead of a run)
31
+ launchKey: null, // bookmarklet auto-start secret (spec 011), lazy-fetched
32
+ bmAuto: true, // "One-click launch (auto-submit)" checkbox
33
+ bmFilter: '', // per-skill bookmarklet filter text
34
+ theme: document.documentElement.dataset.theme || 'dark',
35
+ // GitHub tab
36
+ gh: null, // /api/github payload
37
+ ghFull: false, // true once the "everything open" fetch landed
38
+ ghFullLoading: false,
39
+ ghView: 'issues', // 'issues' | 'prs'
40
+ ghSel: null, // selected item url
41
+ ghWorkflow: null, // workflow chip (null = none — skills/quick-task run)
42
+ ghSkills: new Set(), // skill names toggled on
43
+ ghSkillQuery: '', // filter over the skill chips (long catalogs)
44
+ ghQueued: new Map(), // item url -> run id (client-side "queued" marker)
45
+ lastGhRun: null,
46
+ // Skills tab
47
+ skillsList: null, // /api/skills payload (shared with the GitHub tab chips)
48
+ skillSel: null, // selected skill name, or '__bm' for the bookmarklet panel
49
+ skillQuery: '',
50
+ // Workflows tab — the builder canvas (spec 012)
51
+ wb: null, // {name, description, steps, query, importOpen, importText, importError, copied}
52
+ wbDrag: null, // {from:'palette', skill} | {from:'step', index}
17
53
  };
18
54
 
19
55
  const STATUS_ORDER = { waiting: 0, review: 1, running: 2, queued: 3 };
@@ -37,6 +73,16 @@ function timeAgo(iso) {
37
73
  return `${Math.floor(s / 86400)}d ago`;
38
74
  }
39
75
 
76
+ /* Compact form for the run list — "2m", "1h", "3d". */
77
+ function shortAgo(iso) {
78
+ if (!iso) return '';
79
+ const s = Math.max(0, (Date.now() - new Date(iso).getTime()) / 1000);
80
+ if (s < 60) return `${Math.floor(s)}s`;
81
+ if (s < 3600) return `${Math.floor(s / 60)}m`;
82
+ if (s < 86400) return `${Math.floor(s / 3600)}h`;
83
+ return `${Math.floor(s / 86400)}d`;
84
+ }
85
+
40
86
  function fmtTokens(n) {
41
87
  if (!n) return '0 tok';
42
88
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M tok`;
@@ -49,14 +95,49 @@ function fmtCost(usd) {
49
95
  return `$${usd >= 10 ? usd.toFixed(0) : usd.toFixed(2)}`;
50
96
  }
51
97
 
52
- function prBadge(run) {
98
+ /* Queue position among queued runs (FIFO = createdAt order) — spec 006. */
99
+ function queuePosition(run) {
100
+ const queued = [...state.runs.values()]
101
+ .filter((r) => !r.archived && r.status === 'queued')
102
+ .sort((a, b) => a.createdAt.localeCompare(b.createdAt));
103
+ const idx = queued.findIndex((r) => r.id === run.id);
104
+ return idx >= 0 ? idx + 1 : null;
105
+ }
106
+
107
+ const STATUS_LABEL = {
108
+ waiting: 'needs you',
109
+ review: 'needs review',
110
+ running: 'running',
111
+ queued: 'queued',
112
+ done: 'done',
113
+ failed: 'failed',
114
+ cancelled: 'cancelled',
115
+ };
116
+
117
+ function statusPill(run) {
118
+ const status = run.status;
119
+ const pulse = status === 'waiting' || status === 'running' || status === 'review';
120
+ let label = STATUS_LABEL[status] ?? status;
121
+ if (status === 'queued') {
122
+ const pos = queuePosition(run);
123
+ if (pos) label += ` #${pos}`;
124
+ }
125
+ return `<span class="pill ${esc(status)}">${pulse ? '<span class="pulse-dot"></span>' : ''}${esc(label)}</span>`;
126
+ }
127
+
128
+ function prLink(run) {
53
129
  if (!run.pullRequestUrl) return '';
54
130
  const num = run.pullRequestUrl.split('/').pop();
55
- return `<a class="pr-badge" href="${esc(run.pullRequestUrl)}" target="_blank" rel="noopener">PR #${esc(num)}</a>`;
131
+ return `<a href="${esc(run.pullRequestUrl)}" target="_blank" rel="noopener">PR #${esc(num)}</a>`;
56
132
  }
57
133
 
58
- function badge(status) {
59
- return `<span class="badge ${esc(status)}">${esc(status)}</span>`;
134
+ /* ---- parallel variants (spec 010) ---- */
135
+
136
+ const TERMINAL_STATUSES = ['done', 'failed', 'review', 'cancelled'];
137
+
138
+ /* Group title = any variant's title without its " (A)" suffix. */
139
+ function groupTitle(run) {
140
+ return run.title.replace(/ \([A-C]\)$/, '');
60
141
  }
61
142
 
62
143
  async function getJson(url) {
@@ -65,41 +146,477 @@ async function getJson(url) {
65
146
  return res.json();
66
147
  }
67
148
 
149
+ /* Minimal unified-diff renderer (spec 009) — shared by the "± Diff" panel and
150
+ the review gate. Text parsing only: `diff --git` starts a collapsible
151
+ per-file <details>, +/− lines get colored, @@ hunks and file meta dim.
152
+ Non-diff text (degradation notes) renders as a plain <pre>. ZERO libs. */
153
+ function renderDiff(text) {
154
+ const raw = String(text ?? '').trimEnd();
155
+ if (!raw.trim()) return '<div class="dim">(no changes)</div>';
156
+ if (!raw.includes('diff --git ')) return `<pre>${esc(raw)}</pre>`;
157
+ const out = [];
158
+ let file = null; // { name, lines }
159
+ const flush = () => {
160
+ if (!file) return;
161
+ out.push(
162
+ `<details class="diff-file" open><summary>${esc(file.name)}</summary><pre>${file.lines.join('\n')}</pre></details>`,
163
+ );
164
+ file = null;
165
+ };
166
+ for (const line of raw.split('\n')) {
167
+ if (line.startsWith('diff --git ')) {
168
+ flush();
169
+ const m = / b\/(.+)$/.exec(line);
170
+ file = { name: m ? m[1] : line.slice(11), lines: [] };
171
+ continue;
172
+ }
173
+ if (!file) continue; // preamble before the first file header
174
+ let cls = '';
175
+ if (line.startsWith('+++') || line.startsWith('---')) cls = 'diff-meta';
176
+ else if (line.startsWith('@@')) cls = 'diff-hunk';
177
+ else if (line.startsWith('+')) cls = 'diff-add';
178
+ else if (line.startsWith('-')) cls = 'diff-del';
179
+ else if (/^(index |new file|deleted file|old mode|new mode|similarity|rename |copy |Binary files)/.test(line)) cls = 'diff-meta';
180
+ file.lines.push(cls ? `<span class="${cls}">${esc(line)}</span>` : esc(line));
181
+ }
182
+ flush();
183
+ return out.join('');
184
+ }
185
+
186
+ /* Tiny markdown renderer for the handoff notes — headings, bold, inline code,
187
+ fenced code, lists, links, hr. Escape-first, line-based, ZERO libs. Not a
188
+ full parser; handoff files are simple and anything unrecognized falls
189
+ through as a plain paragraph. */
190
+ function renderMarkdown(src) {
191
+ const lines = String(src ?? '').replace(/\r\n?/g, '\n').split('\n');
192
+ const out = [];
193
+ let list = null; // 'ul' | 'ol'
194
+ let code = null; // collected fenced-code lines
195
+ let quote = false; // inside a > blockquote
196
+ const closeList = () => {
197
+ if (list) {
198
+ out.push(`</${list}>`);
199
+ list = null;
200
+ }
201
+ };
202
+ const closeQuote = () => {
203
+ if (quote) {
204
+ out.push('</blockquote>');
205
+ quote = false;
206
+ }
207
+ };
208
+ const inline = (s) => {
209
+ let h = esc(s);
210
+ h = h.replace(/`([^`]+)`/g, '<code>$1</code>');
211
+ h = h.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
212
+ h = h.replace(/\[([^\]]+)\]\((https?:[^)\s]+)\)/g, '<a href="$2" target="_blank" rel="noopener">$1</a>');
213
+ h = h.replace(/(^|\s)(https?:\/\/[^\s<]+)/g, '$1<a href="$2" target="_blank" rel="noopener">$2</a>');
214
+ return h;
215
+ };
216
+ for (const line of lines) {
217
+ if (code) {
218
+ if (/^```/.test(line)) {
219
+ out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`);
220
+ code = null;
221
+ } else {
222
+ code.push(line);
223
+ }
224
+ continue;
225
+ }
226
+ if (/^```/.test(line)) {
227
+ closeList();
228
+ closeQuote();
229
+ code = [];
230
+ continue;
231
+ }
232
+ const bq = /^>\s?(.*)$/.exec(line);
233
+ if (bq) {
234
+ if (!quote) {
235
+ closeList();
236
+ out.push('<blockquote>');
237
+ quote = true;
238
+ }
239
+ if (bq[1].trim()) out.push(`<p>${inline(bq[1])}</p>`);
240
+ continue;
241
+ }
242
+ closeQuote();
243
+ const heading = /^(#{1,4})\s+(.*)$/.exec(line);
244
+ if (heading) {
245
+ closeList();
246
+ const level = heading[1].length;
247
+ out.push(`<h${level}>${inline(heading[2])}</h${level}>`);
248
+ continue;
249
+ }
250
+ if (/^\s*(---+|\*\*\*+)\s*$/.test(line)) {
251
+ closeList();
252
+ out.push('<hr>');
253
+ continue;
254
+ }
255
+ const ul = /^\s*[-*]\s+(.*)$/.exec(line);
256
+ const ol = /^\s*\d+[.)]\s+(.*)$/.exec(line);
257
+ if (ul || ol) {
258
+ const kind = ul ? 'ul' : 'ol';
259
+ if (list !== kind) {
260
+ closeList();
261
+ out.push(`<${kind}>`);
262
+ list = kind;
263
+ }
264
+ const content = (ul ?? ol)[1];
265
+ const task = /^\[( |x|X)\]\s+(.*)$/.exec(content);
266
+ out.push(
267
+ task
268
+ ? `<li class="task"><span class="cb">${task[1].trim() ? '☑' : '☐'}</span>${inline(task[2])}</li>`
269
+ : `<li>${inline(content)}</li>`,
270
+ );
271
+ continue;
272
+ }
273
+ closeList();
274
+ if (line.trim()) out.push(`<p>${inline(line)}</p>`);
275
+ }
276
+ if (code) out.push(`<pre><code>${esc(code.join('\n'))}</code></pre>`); // unclosed fence
277
+ closeList();
278
+ closeQuote();
279
+ return out.join('\n');
280
+ }
281
+
68
282
  // ---- boot ------------------------------------------------------------------
69
283
 
70
284
  async function init() {
71
285
  bindUi();
72
- const [health, workflowsRes, runs] = await Promise.all([
286
+ applyTheme(state.theme);
287
+ const [health, workflowsRes, runs, todos, skills, uiState] = await Promise.all([
73
288
  getJson('/api/health'),
74
289
  getJson('/api/workflows'),
75
290
  getJson('/api/runs'),
291
+ getJson('/api/todos').catch(() => []),
292
+ getJson('/api/skills').catch(() => []), // the form's skill mode + GitHub chips
293
+ getJson('/api/ui-state').catch(() => ({})),
76
294
  ]);
77
- renderHeader(health);
78
- state.workflows = workflowsRes.workflows;
79
- const select = $('#new-task select[name=workflow]');
80
- select.innerHTML = state.workflows
81
- .map((w) => `<option value="${esc(w.name)}" title="${esc(w.description ?? '')}">${esc(w.name)}</option>`)
82
- .join('');
295
+ state.todos = todos;
296
+ state.skillsList = skills;
297
+ renderInboxBadge();
298
+ renderChrome(health);
299
+ // Preselect what you actually run: the last-used source (persisted in
300
+ // .ai/cezar/ui-state.json), else the first skill, else the first workflow.
301
+ const last = uiState.lastTask;
302
+ const lastValid =
303
+ last &&
304
+ (last.source === 'skill'
305
+ ? skills.some((s) => s.name === last.ref)
306
+ : workflowsRes.workflows.some((w) => w.name === last.ref));
307
+ const pick = lastValid ? last : defaultTaskSource(workflowsRes.workflows);
308
+ state.taskSource = pick.source;
309
+ state.taskRef = pick.ref;
310
+ setWorkflowOptions(workflowsRes.workflows);
83
311
  for (const run of runs) state.runs.set(run.id, run);
84
312
  renderRunList();
85
313
  connectGlobal();
86
- const latest = sortedRuns()[0];
87
- if (latest) selectRun(latest.id);
314
+ const deepLinked = await handleDeepLink();
315
+ if (!deepLinked) {
316
+ const latest = sortedRuns()[0];
317
+ if (latest) selectRun(latest.id);
318
+ }
88
319
  }
89
320
 
90
- function renderHeader(health) {
91
- const repoChip = $('#repo-chip');
92
- if (health.repo) {
93
- repoChip.hidden = false;
94
- repoChip.textContent = `${health.repo.root.split('/').pop()} · ${health.repo.branch}`;
321
+ function applyTheme(theme) {
322
+ state.theme = theme;
323
+ document.documentElement.dataset.theme = theme;
324
+ try {
325
+ localStorage.setItem('cez-theme', theme);
326
+ } catch {
327
+ // private mode — the toggle still works for this page
328
+ }
329
+ const btn = $('#theme-toggle');
330
+ if (btn) btn.textContent = theme === 'dark' ? 'LIGHT ☼' : 'DARK ☾';
331
+ }
332
+
333
+ // ---- bookmarklet deep-link (spec 011) ----------------------------------------
334
+
335
+ /* `/new?skill=<name>&ref=<github-url>&auto=1&key=<launchKey>` — opened by a
336
+ bookmarklet clicked on a GitHub PR/issue. `auto=1` + the correct launch-key
337
+ starts the run immediately; anything else (no auto, bad key, a drive-by
338
+ page guessing the URL) only prefills the form — the user presses Run.
339
+ Returns true when a run was started (and selected). */
340
+ async function handleDeepLink() {
341
+ const params = new URLSearchParams(location.search);
342
+ if (location.pathname !== '/new' && !params.has('skill') && !params.has('ref')) return false;
343
+ const skill = (params.get('skill') ?? '').trim();
344
+ const ref = (params.get('ref') ?? params.get('task') ?? '').trim();
345
+ const auto = params.get('auto') === '1';
346
+ const key = params.get('key') ?? '';
347
+ history.replaceState({}, '', '/'); // never re-trigger on reload
348
+ if (!ref) return false;
349
+
350
+ if (auto) {
351
+ let launchKey = '';
352
+ try {
353
+ launchKey = (await getJson('/api/launch-key')).key;
354
+ } catch {
355
+ // fall through to the blocked path
356
+ }
357
+ if (launchKey && key === launchKey) {
358
+ // Per-skill: one inline step (the spec-008 API); no skill: quick-task.
359
+ const body = skill
360
+ ? { steps: [{ id: 'task', name: skill, skill, prompt: ref }], task: ref }
361
+ : { workflow: 'quick-task', task: ref };
362
+ try {
363
+ const res = await fetch('/api/runs', {
364
+ method: 'POST',
365
+ headers: { 'content-type': 'application/json' },
366
+ body: JSON.stringify(body),
367
+ });
368
+ const data = await res.json();
369
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
370
+ handleStarted(data);
371
+ alertBar(skill ? `Started "${skill}" on ${oneLine(ref)}` : `Started task on ${oneLine(ref)}`);
372
+ return true;
373
+ } catch (err) {
374
+ alertBar(`Auto-start failed: ${err.message} — review the form and press Run`);
375
+ }
376
+ } else {
377
+ alertBar('auto-launch blocked (bad key) — press Run');
378
+ }
379
+ }
380
+
381
+ // Prefill path: the form carries everything; quick-task (or the planner)
382
+ // resolves a named skill from the task text — zero extra UI.
383
+ const form = $('#new-task');
384
+ form.task.value = skill ? `Use the "${skill}" skill on: ${ref}` : ref;
385
+ if (state.workflows.some((w) => w.name === 'quick-task')) {
386
+ state.taskSource = 'workflow';
387
+ state.taskRef = 'quick-task';
388
+ renderTaskPills();
389
+ }
390
+ if (!auto) alertBar('Form prefilled from GitHub — review & press Run');
391
+ $('#run-btn').focus();
392
+ return false;
393
+ }
394
+
395
+ /* Skills first (feedback 2026-07-11): the natural default is a skill, not a
396
+ chain — workflows stay one tab away in the picker. */
397
+ function defaultTaskSource(workflows = state.workflows) {
398
+ const firstSkill = (state.skillsList ?? [])[0];
399
+ if (firstSkill) return { source: 'skill', ref: firstSkill.name };
400
+ return { source: 'workflow', ref: workflows[0]?.name ?? 'quick-task' };
401
+ }
402
+
403
+ function setWorkflowOptions(workflows) {
404
+ state.workflows = workflows;
405
+ const refValid =
406
+ state.taskRef &&
407
+ (state.taskSource === 'skill'
408
+ ? (state.skillsList ?? []).some((s) => s.name === state.taskRef)
409
+ : state.workflows.some((w) => w.name === state.taskRef));
410
+ if (!refValid) {
411
+ const pick = defaultTaskSource(workflows);
412
+ state.taskSource = pick.source;
413
+ state.taskRef = pick.ref;
414
+ }
415
+ renderTaskPills();
416
+ // GitHub's workflow chip is optional (null = run skills or quick-task) —
417
+ // only clear it when it names a workflow that no longer exists.
418
+ if (state.ghWorkflow && !state.workflows.some((w) => w.name === state.ghWorkflow)) {
419
+ state.ghWorkflow = null;
420
+ }
421
+ }
422
+
423
+ /* Remember what was just run so the next session preselects it. Fire-and-
424
+ forget — a failed write only costs the convenience. */
425
+ function saveLastTaskSource() {
426
+ if (!state.taskRef) return;
427
+ void fetch('/api/ui-state', {
428
+ method: 'PUT',
429
+ headers: { 'content-type': 'application/json' },
430
+ body: JSON.stringify({ lastTask: { source: state.taskSource, ref: state.taskRef } }),
431
+ }).catch(() => {});
432
+ }
433
+
434
+ /* ---- the form's pill dropdowns — "≡ fix-and-verify ⌄" and "⊞ auto ⌄" ---- */
435
+
436
+ const PILL_ICONS = {
437
+ chain: 'M4 6h16M4 12h16M4 18h10', // ≡ list
438
+ skill: 'M4 19.5A2.5 2.5 0 016.5 17H20M6.5 2H20v20H6.5A2.5 2.5 0 014 19.5v-15A2.5 2.5 0 016.5 2z', // book
439
+ model: 'M9 3v3M15 3v3M9 18v3M15 18v3M3 9h3M3 15h3M18 9h3M18 15h3M6 6h12v12H6z', // chip
440
+ };
441
+
442
+ /* Small inline icons for the run-detail action bar (design: every action has
443
+ a glyph, not typography like "±" / "▶"). Stroke icons by default; `fill`
444
+ for solid play/stop. */
445
+ function biIcon(d, fill = false) {
446
+ return `<svg class="bi${fill ? ' bi-fill' : ''}" viewBox="0 0 24 24"><path d="${d}"/></svg>`;
447
+ }
448
+ const BI = {
449
+ check: biIcon('M5 12l5 5 9-11'),
450
+ play: biIcon('M6 4l14 8-14 8V4z', true),
451
+ stop: biIcon('M7 7h10v10H7z', true),
452
+ terminal: biIcon('M4 17l6-5-6-5M12 19h8'),
453
+ diff: biIcon('M9 5v6M6 8h6M6 16h6M16 5v14'),
454
+ notes: biIcon('M6 3h9l4 4v14H6V3zM15 3v4h4M9 12h7M9 16h5'),
455
+ folder: biIcon('M3 8a2 2 0 012-2h4l2 2h8a2 2 0 012 2v8a2 2 0 01-2 2H5a2 2 0 01-2-2V8zM9 14h6'),
456
+ archive: biIcon('M4 5h16v4H4zM6 9v10h12V9M10 13h4'),
457
+ trash: biIcon('M4 7h16M10 7V5h4v2M6 7l1 13h10l1-13M10 11v6M14 11v6'),
458
+ };
459
+
460
+ function pillHtml(iconPath, label, menuHtml) {
461
+ return `
462
+ <button type="button" class="pill-btn">
463
+ <svg class="pic" viewBox="0 0 24 24"><path d="${iconPath}"/></svg>
464
+ <span class="pl">${esc(label)}</span>
465
+ <svg class="chev" viewBox="0 0 24 24"><path d="M6 9l6 6 6-6"/></svg>
466
+ </button>
467
+ <div class="pill-menu" hidden>${menuHtml}</div>`;
468
+ }
469
+
470
+ function menuItemHtml(data, title, desc, selected, iconPath) {
471
+ return `
472
+ <div class="menu-item ${selected ? 'on' : ''}" ${data}>
473
+ <div class="mi-title"><span class="chk">${selected ? '✓' : ''}</span>${
474
+ iconPath ? `<svg class="mi-ic" viewBox="0 0 24 24"><path d="${iconPath}"/></svg>` : ''
475
+ }${esc(title)}</div>
476
+ ${desc ? `<div class="mi-desc">${esc(desc)}</div>` : ''}
477
+ </div>`;
478
+ }
479
+
480
+ /* One pill covers chains AND skills: a search box + a Workflows|Skills tab
481
+ inside the menu ("zero new concepts": you pick what runs, the kind is
482
+ implicit in where you found it). */
483
+ function srcMenuItemsHtml() {
484
+ const q = state.srcMenuQuery.trim().toLowerCase();
485
+ const items =
486
+ state.srcMenuTab === 'skill'
487
+ ? (state.skillsList ?? []).map((s) => ({ name: s.name, desc: s.description, source: 'skill' }))
488
+ : state.workflows.map((w) => ({ name: w.name, desc: w.description, source: 'workflow' }));
489
+ const filtered = items.filter(
490
+ (i) => !q || i.name.toLowerCase().includes(q) || (i.desc ?? '').toLowerCase().includes(q),
491
+ );
492
+ if (!filtered.length) {
493
+ return `<div class="menu-empty">${
494
+ state.srcMenuTab === 'skill' && !(state.skillsList ?? []).length
495
+ ? 'No skills yet — drop Markdown files into .ai/skills/'
496
+ : '(nothing matches)'
497
+ }</div>`;
498
+ }
499
+ return filtered
500
+ .map((i) =>
501
+ menuItemHtml(
502
+ `data-mi="src" data-source="${i.source}" data-value="${esc(i.name)}"`,
503
+ i.name,
504
+ i.desc,
505
+ state.taskSource === i.source && state.taskRef === i.name,
506
+ i.source === 'skill' ? SKILL_ICON : PILL_ICONS.chain,
507
+ ),
508
+ )
509
+ .join('');
510
+ }
511
+
512
+ function renderTaskPills() {
513
+ const srcMenu = `
514
+ <div class="menu-search">
515
+ <svg viewBox="0 0 24 24"><circle cx="11" cy="11" r="7"/><path d="M21 21l-5-5"/></svg>
516
+ <input id="src-search" type="text" placeholder="Search…" autocomplete="off">
517
+ </div>
518
+ <div class="menu-tabs">
519
+ <button type="button" data-mtab="workflow" class="${state.srcMenuTab === 'workflow' ? 'active' : ''}">Workflows</button>
520
+ <button type="button" data-mtab="skill" class="${state.srcMenuTab === 'skill' ? 'active' : ''}">Skills</button>
521
+ </div>
522
+ <div id="src-menu-items">${srcMenuItemsHtml()}</div>`;
523
+ $('#src-pill').innerHTML = pillHtml(
524
+ state.taskSource === 'skill' ? PILL_ICONS.skill : PILL_ICONS.chain,
525
+ state.taskRef ?? 'quick-task',
526
+ srcMenu,
527
+ );
528
+
529
+ const models = state.modelsAvailable ? CLAUDE_MODELS : CLAUDE_MODELS.slice(0, 1);
530
+ const selectedModel = models.find((m) => m.id === state.taskModel) ?? models[0];
531
+ const modelMenu = models
532
+ .map((m) =>
533
+ menuItemHtml(
534
+ `data-mi="model" data-value="${esc(m.id)}"`,
535
+ m.label,
536
+ m.desc,
537
+ m.id === (selectedModel?.id ?? ''),
538
+ PILL_ICONS.model,
539
+ ),
540
+ )
541
+ .join('');
542
+ $('#model-pill').innerHTML = pillHtml(PILL_ICONS.model, selectedModel?.label ?? 'auto', modelMenu);
543
+ }
544
+
545
+ function closePillMenus() {
546
+ for (const el of document.querySelectorAll('.pill-select.open')) {
547
+ el.classList.remove('open');
548
+ const menu = el.querySelector('.pill-menu');
549
+ if (menu) menu.hidden = true;
95
550
  }
551
+ }
552
+
553
+ function renderChrome(health) {
554
+ const repoChip = $('#repo-chip');
555
+ repoChip.hidden = false;
556
+ repoChip.textContent = health.repo
557
+ ? `${health.repo.root.split('/').pop()} / ${health.repo.branch}`
558
+ : 'no git — tasks run in place';
559
+ repoChip.title = health.repo ? `${health.repo.root} · ${health.repo.branch}` : 'not a git repo — tasks run in place, one at a time';
96
560
  $('#env-chips').innerHTML = health.checks
97
- .map((c) => `<span class="chip ${c.available ? 'ok' : 'bad'}" title="${esc(c.hint ?? c.version ?? '')}">${c.available ? '✓' : '✗'} ${esc(c.name)}</span>`)
561
+ .map(
562
+ (c) =>
563
+ `<span class="env-chip ${c.available ? 'ok' : 'bad'}" title="${esc(c.hint ?? c.version ?? '')}"><span class="led"></span>${esc(c.name)}</span>`,
564
+ )
98
565
  .join('');
566
+
567
+ // Model pill fed by what's actually connected: claude CLI present → the
568
+ // Claude catalog; otherwise only "auto".
569
+ state.modelsAvailable = health.checks.some((c) => c.name === 'claude' && c.available);
570
+ renderTaskPills();
571
+ }
572
+
573
+ /* What `claude --model` accepts: "auto" (no flag — each step decides), the
574
+ stable tier aliases (they track the newest release), then current pinned
575
+ versions for reproducible runs. */
576
+ const CLAUDE_MODELS = [
577
+ { id: '', label: 'auto', desc: 'Pick the best model per step' },
578
+ { id: 'opus', label: 'opus', desc: 'Deep reasoning for hard tasks' },
579
+ { id: 'sonnet', label: 'sonnet', desc: 'Fast and cheap' },
580
+ { id: 'haiku', label: 'haiku', desc: 'Fastest — simple, scoped tasks' },
581
+ { id: 'claude-opus-4-8', label: 'Opus 4.8', desc: 'Pinned version' },
582
+ { id: 'claude-sonnet-5', label: 'Sonnet 5', desc: 'Pinned version' },
583
+ { id: 'claude-haiku-4-5', label: 'Haiku 4.5', desc: 'Pinned version' },
584
+ ];
585
+
586
+ /* The global stream replays nothing after a drop (laptop sleep, server
587
+ restart) — a missed `run` event would leave a stale status in the sidebar
588
+ forever (seen live: a run resting at `review` still listed under Working).
589
+ Every (re)connect and every return to a visible tab re-syncs the full run
590
+ list instead. */
591
+ let lastResyncAt = 0;
592
+ async function resyncRuns() {
593
+ if (Date.now() - lastResyncAt < 2_000) return; // boot + onopen double-fire guard
594
+ lastResyncAt = Date.now();
595
+ try {
596
+ const runs = await getJson('/api/runs');
597
+ const fresh = new Set(runs.map((r) => r.id));
598
+ for (const id of [...state.runs.keys()]) if (!fresh.has(id)) state.runs.delete(id);
599
+ for (const run of runs) state.runs.set(run.id, run);
600
+ renderRunList();
601
+ const sel = state.selectedId ? state.runs.get(state.selectedId) : null;
602
+ if (sel) {
603
+ updateDetail(sel);
604
+ } else if (state.selectedId) {
605
+ state.selectedId = null;
606
+ $('#detail').innerHTML = '<div class="empty">Select a run — or start one.</div>';
607
+ }
608
+ } catch {
609
+ // offline — the next reconnect/visibility flip retries
610
+ }
99
611
  }
100
612
 
101
613
  function connectGlobal() {
102
614
  const es = new EventSource('/api/events');
615
+ es.onopen = () => void resyncRuns(); // fires on the initial connect AND every auto-reconnect
616
+ document.addEventListener('visibilitychange', () => {
617
+ // SSE can die silently across a sleep — a tab coming back re-syncs too.
618
+ if (!document.hidden) void resyncRuns();
619
+ });
103
620
  es.addEventListener('run', (e) => {
104
621
  const run = JSON.parse(e.data);
105
622
  state.runs.set(run.id, run);
@@ -115,11 +632,20 @@ function connectGlobal() {
115
632
  $('#detail').innerHTML = '<div class="empty">Select a run — or start one.</div>';
116
633
  }
117
634
  });
635
+ es.addEventListener('todos', (e) => {
636
+ state.todos = JSON.parse(e.data);
637
+ renderInboxBadge();
638
+ if (!$('#view-inbox').hidden) renderInbox();
639
+ });
118
640
  }
119
641
 
120
642
  // ---- UI events -------------------------------------------------------------
121
643
 
122
644
  function bindUi() {
645
+ $('#theme-toggle').addEventListener('click', () => {
646
+ applyTheme(state.theme === 'dark' ? 'light' : 'dark');
647
+ });
648
+
123
649
  $('#tabs').addEventListener('click', (e) => {
124
650
  const btn = e.target.closest('button[data-view]');
125
651
  if (!btn) return;
@@ -129,20 +655,230 @@ function bindUi() {
129
655
  view.hidden = false;
130
656
  if (btn.dataset.view === 'repo') loadRepo();
131
657
  if (btn.dataset.view === 'skills') loadSkills();
658
+ if (btn.dataset.view === 'inbox') renderInbox();
659
+ if (btn.dataset.view === 'github') loadGithub();
660
+ if (btn.dataset.view === 'workflows') openWorkflowsView();
661
+ });
662
+
663
+ $('#view-inbox').addEventListener('click', async (e) => {
664
+ const goto = e.target.closest('[data-goto-run]');
665
+ if (goto) {
666
+ e.preventDefault();
667
+ showRunsView();
668
+ selectRun(goto.dataset.gotoRun);
669
+ return;
670
+ }
671
+ const btn = e.target.closest('button[data-todo-action]');
672
+ if (!btn) return;
673
+ const id = btn.closest('.todo-card')?.dataset.id;
674
+ if (!id) return;
675
+ if (btn.dataset.todoAction === 'remove') {
676
+ await fetch(`/api/todos/${id}`, { method: 'DELETE' });
677
+ state.todos = state.todos.filter((t) => t.id !== id);
678
+ renderInboxBadge();
679
+ renderInbox();
680
+ } else if (btn.dataset.todoAction === 'start') {
681
+ btn.disabled = true;
682
+ try {
683
+ const res = await fetch(`/api/todos/${id}/start`, { method: 'POST' });
684
+ const data = await res.json().catch(() => ({}));
685
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
686
+ const todo = state.todos.find((t) => t.id === id);
687
+ if (todo) todo.startedTaskId = data.run.id;
688
+ renderInboxBadge();
689
+ renderInbox();
690
+ state.runs.set(data.run.id, data.run);
691
+ showRunsView();
692
+ renderRunList();
693
+ selectRun(data.run.id);
694
+ } catch (err) {
695
+ alertBar(err.message);
696
+ btn.disabled = false;
697
+ }
698
+ }
699
+ });
700
+
701
+ bindGithubView();
702
+ bindSkillsView();
703
+ bindWorkflowsView();
704
+ bindRepoView();
705
+
706
+ const taskForm = $('#new-task');
707
+
708
+ // Pill dropdowns: toggle on the pill, select on a menu item, close on any
709
+ // outside click (one document listener; menus are re-rendered per change).
710
+ document.addEventListener('click', (e) => {
711
+ const pill = e.target.closest('.pill-select');
712
+ if (!pill) {
713
+ closePillMenus();
714
+ return;
715
+ }
716
+ const item = e.target.closest('.menu-item[data-mi]');
717
+ if (item) {
718
+ if (item.dataset.mi === 'src') {
719
+ state.taskSource = item.dataset.source;
720
+ state.taskRef = item.dataset.value;
721
+ } else if (item.dataset.mi === 'model') {
722
+ state.taskModel = item.dataset.value;
723
+ }
724
+ closePillMenus();
725
+ renderTaskPills();
726
+ return;
727
+ }
728
+ // Workflows | Skills switch inside the source menu.
729
+ const mtab = e.target.closest('button[data-mtab]');
730
+ if (mtab) {
731
+ state.srcMenuTab = mtab.dataset.mtab;
732
+ for (const b of mtab.parentElement.children) b.classList.toggle('active', b === mtab);
733
+ const box = $('#src-menu-items');
734
+ if (box) box.innerHTML = srcMenuItemsHtml();
735
+ $('#src-search')?.focus();
736
+ return;
737
+ }
738
+ if (e.target.closest('.menu-search')) return; // typing, not toggling
739
+ if (e.target.closest('.pill-btn')) {
740
+ const menu = pill.querySelector('.pill-menu');
741
+ const wasOpen = pill.classList.contains('open');
742
+ closePillMenus();
743
+ if (!wasOpen && menu) {
744
+ pill.classList.add('open');
745
+ menu.hidden = false;
746
+ // Fresh view on open: Skills tab by default (feedback 2026-07-11 —
747
+ // skills are what people pick 9 times out of 10), empty query,
748
+ // focused search.
749
+ if (pill.id === 'src-pill') {
750
+ state.srcMenuTab = 'skill';
751
+ state.srcMenuQuery = '';
752
+ const search = $('#src-search');
753
+ if (search) search.value = '';
754
+ for (const b of menu.querySelectorAll('button[data-mtab]')) {
755
+ b.classList.toggle('active', b.dataset.mtab === state.srcMenuTab);
756
+ }
757
+ const box = $('#src-menu-items');
758
+ if (box) box.innerHTML = srcMenuItemsHtml();
759
+ search?.focus();
760
+ }
761
+ }
762
+ }
763
+ });
764
+
765
+ // Live filter — re-render only the item list so the input keeps focus.
766
+ document.addEventListener('input', (e) => {
767
+ if (e.target.id !== 'src-search') return;
768
+ state.srcMenuQuery = e.target.value;
769
+ const box = $('#src-menu-items');
770
+ if (box) box.innerHTML = srcMenuItemsHtml();
771
+ });
772
+ // Enter in the search picks the first match (and never submits the form).
773
+ document.addEventListener('keydown', (e) => {
774
+ if (e.target.id !== 'src-search' || e.key !== 'Enter') return;
775
+ e.preventDefault();
776
+ $('#src-menu-items .menu-item')?.click();
777
+ });
778
+
779
+ // 📎 — attach images to the task (same pipeline as ⌘V paste).
780
+ const taskFile = $('#task-file');
781
+ $('#task-attach').addEventListener('click', () => taskFile.click());
782
+ taskFile.addEventListener('change', () => {
783
+ for (const file of taskFile.files ?? []) {
784
+ void readImageFile(file).then((img) => {
785
+ if (!img || state.taskImages.length >= 4) return;
786
+ state.taskImages.push(img);
787
+ renderTaskThumbs();
788
+ });
789
+ }
790
+ taskFile.value = '';
791
+ });
792
+
793
+ // ⌘↵ / Ctrl+↵ submits from inside the textarea.
794
+ taskForm.task.addEventListener('keydown', (e) => {
795
+ if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) {
796
+ e.preventDefault();
797
+ taskForm.requestSubmit();
798
+ }
799
+ });
800
+
801
+ // The task box grows on focus and with content, springs back when left
802
+ // empty. Explicit px heights so the CSS height transition animates.
803
+ const taskBox = taskForm.task;
804
+ const autosizeTask = () => {
805
+ const engaged = document.activeElement === taskBox || taskBox.value.trim();
806
+ const floor = engaged ? 92 : 40;
807
+ const prev = taskBox.style.height || '40px';
808
+ taskBox.style.height = 'auto';
809
+ const target = Math.max(floor, Math.min(taskBox.scrollHeight, 220));
810
+ taskBox.style.height = prev; // restore the start point…
811
+ void taskBox.offsetHeight; // …force a reflow…
812
+ taskBox.style.height = `${target}px`; // …then animate to the target
813
+ };
814
+ taskBox.addEventListener('focus', autosizeTask);
815
+ taskBox.addEventListener('input', autosizeTask);
816
+ taskBox.addEventListener('blur', autosizeTask);
817
+
818
+ // Drop target for GitHub rows (and any dragged text): prefill the task box
819
+ // with the dragged prompt, then pick a skill/workflow and press Run.
820
+ taskBox.addEventListener('dragover', (e) => {
821
+ if (e.dataTransfer?.types.includes('text/plain')) {
822
+ e.preventDefault();
823
+ e.dataTransfer.dropEffect = 'copy';
824
+ }
825
+ });
826
+ taskBox.addEventListener('drop', (e) => {
827
+ const text = e.dataTransfer?.getData('text/plain');
828
+ if (!text) return;
829
+ e.preventDefault();
830
+ taskBox.value = text;
831
+ taskBox.focus();
832
+ taskBox.dispatchEvent(new Event('input')); // autosize to the content
833
+ });
834
+
835
+ // Screenshots pasted into the task box travel with POST /api/runs and reach
836
+ // the first agent step's opening message.
837
+ taskBox.addEventListener('paste', (e) => {
838
+ const items = [...(e.clipboardData?.items ?? [])].filter((i) => i.type.startsWith('image/'));
839
+ if (!items.length) return;
840
+ e.preventDefault();
841
+ for (const item of items) {
842
+ const file = item.getAsFile();
843
+ if (file) {
844
+ void readImageFile(file).then((img) => {
845
+ if (!img || state.taskImages.length >= 4) return;
846
+ state.taskImages.push(img);
847
+ renderTaskThumbs();
848
+ });
849
+ }
850
+ }
851
+ });
852
+ $('#task-thumbs').addEventListener('click', (e) => {
853
+ const thumb = e.target.closest('[data-idx]');
854
+ if (!thumb) return;
855
+ state.taskImages.splice(Number(thumb.dataset.idx), 1);
856
+ renderTaskThumbs();
132
857
  });
133
858
 
134
- $('#new-task').addEventListener('submit', async (e) => {
859
+ taskForm.addEventListener('submit', async (e) => {
135
860
  e.preventDefault();
136
861
  const form = e.target;
137
862
  const errorBox = $('#form-error');
138
863
  errorBox.hidden = true;
139
864
  const body = {
140
865
  task: form.task.value.trim(),
141
- workflow: form.workflow.value,
142
- model: form.model.value.trim() || undefined,
866
+ model: state.taskModel || undefined,
867
+ variants: state.variants > 1 ? state.variants : undefined,
868
+ images: state.taskImages.length
869
+ ? state.taskImages.map((i) => ({ mediaType: i.mediaType, data: i.data }))
870
+ : undefined,
143
871
  };
144
872
  if (!body.task) return;
145
- form.querySelector('button').disabled = true;
873
+ if (state.taskSource === 'skill' && state.taskRef) {
874
+ // A skill runs as a one-step inline chain — same shape the inbox and
875
+ // the bookmarklet auto-start use (spec 008's API).
876
+ body.steps = [{ id: 'task', name: state.taskRef, skill: state.taskRef, prompt: '{{task}}' }];
877
+ } else {
878
+ body.workflow = state.taskRef ?? 'quick-task';
879
+ }
880
+ discardPlan(); // a plain Run supersedes any pending plan (spec 008)
881
+ $('#run-btn').disabled = true;
146
882
  try {
147
883
  const res = await fetch('/api/runs', {
148
884
  method: 'POST',
@@ -152,21 +888,44 @@ function bindUi() {
152
888
  const data = await res.json();
153
889
  if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
154
890
  form.task.value = '';
155
- state.runs.set(data.id, data);
156
- renderRunList();
157
- selectRun(data.id);
891
+ state.taskImages = [];
892
+ renderTaskThumbs();
893
+ form.task.dispatchEvent(new Event('blur')); // shrink the box back
894
+ saveLastTaskSource();
895
+ handleStarted(data);
158
896
  } catch (err) {
159
897
  errorBox.textContent = err.message;
160
898
  errorBox.hidden = false;
161
899
  } finally {
162
- form.querySelector('button').disabled = false;
900
+ $('#run-btn').disabled = false;
163
901
  }
164
902
  });
165
903
 
904
+ bindPlanPanel();
905
+
906
+ // Parallel variants (spec 010) have no form control right now — the ×1/×2/×3
907
+ // switch was retired from the UI. The backend path stays: state.variants is
908
+ // still sent with POST /api/runs whenever something sets it above 1.
909
+
166
910
  $('#run-list').addEventListener('click', (e) => {
167
- if (e.target.closest('a')) return; // PR links navigate, not select
911
+ if (e.target.closest('a')) return; // links navigate, not select
912
+ const compare = e.target.closest('button[data-compare]');
913
+ if (compare) {
914
+ void selectGroup(compare.dataset.compare);
915
+ return;
916
+ }
168
917
  const item = e.target.closest('.run-item');
169
- if (item) selectRun(item.dataset.id);
918
+ if (!item) return;
919
+ if (item.dataset.id) {
920
+ showRunsView();
921
+ selectRun(item.dataset.id);
922
+ } else if (item.dataset.group) {
923
+ // Group tile: toggle the variant list under it (in-memory UI state).
924
+ const gid = item.dataset.group;
925
+ if (state.expandedGroups.has(gid)) state.expandedGroups.delete(gid);
926
+ else state.expandedGroups.add(gid);
927
+ renderRunList();
928
+ }
170
929
  });
171
930
 
172
931
  $('#list-tabs').addEventListener('click', async (e) => {
@@ -181,6 +940,19 @@ function bindUi() {
181
940
  });
182
941
 
183
942
  $('#detail').addEventListener('click', async (e) => {
943
+ // Agent screenshots zoom into a lightbox.
944
+ const shot = e.target.closest('[data-lightbox]');
945
+ if (shot) {
946
+ openLightbox(shot.dataset.lightbox, shot.dataset.name);
947
+ return;
948
+ }
949
+ // Compare view (spec 010): "Pick this one" lives in #detail without a
950
+ // selected run — handle it before the per-run actions.
951
+ const pick = e.target.closest('button[data-pick]');
952
+ if (pick) {
953
+ void pickVariant(pick);
954
+ return;
955
+ }
184
956
  const btn = e.target.closest('button[data-action]');
185
957
  if (!btn) return;
186
958
  const id = state.selectedId;
@@ -224,6 +996,84 @@ function bindUi() {
224
996
  alertBar(data.error ?? 'cannot open terminal');
225
997
  }
226
998
  }
999
+ } else if (btn.dataset.action === 'diff') {
1000
+ const panel = $('#diff-panel');
1001
+ if (!panel) return;
1002
+ if (!panel.hidden) {
1003
+ panel.hidden = true;
1004
+ return;
1005
+ }
1006
+ panel.hidden = false;
1007
+ $('#diff-body').innerHTML = '<div class="dim">Loading…</div>';
1008
+ try {
1009
+ const res = await fetch(`/api/runs/${id}/diff`);
1010
+ const text = await res.text();
1011
+ $('#diff-body').innerHTML = text.trim() ? renderDiff(text) : '<div class="dim">(no changes yet)</div>';
1012
+ } catch (err) {
1013
+ $('#diff-body').textContent = `✗ ${err.message}`;
1014
+ }
1015
+ } else if (btn.dataset.action === 'send-back') {
1016
+ // Review gate (spec 009): the notes go back into the same session via
1017
+ // "Continue" — the run leaves `review`, works, and gates again.
1018
+ const notes = $('#review-notes')?.value.trim();
1019
+ if (!notes) {
1020
+ alertBar('Write what to change first.');
1021
+ $('#review-notes')?.focus();
1022
+ return;
1023
+ }
1024
+ btn.disabled = true;
1025
+ const res = await fetch(`/api/runs/${id}/continue`, {
1026
+ method: 'POST',
1027
+ headers: { 'content-type': 'application/json' },
1028
+ body: JSON.stringify({ text: `Review feedback:\n${notes}` }),
1029
+ });
1030
+ if (!res.ok) {
1031
+ const data = await res.json().catch(() => ({}));
1032
+ alertBar(data.error ?? 'cannot send back');
1033
+ btn.disabled = false;
1034
+ }
1035
+ // on success the SSE run update flips the status and hides the panel
1036
+ } else if (btn.dataset.action === 'draft-pr') {
1037
+ btn.disabled = true;
1038
+ const res = await fetch(`/api/runs/${id}/pr`, { method: 'POST' });
1039
+ const data = await res.json().catch(() => ({}));
1040
+ if (res.ok) {
1041
+ alertBar(`Draft PR created — ${data.url}`);
1042
+ } else {
1043
+ alertBar(data.error ?? 'PR creation failed');
1044
+ const manual = $('#review-manual');
1045
+ if (manual && data.manual) {
1046
+ manual.hidden = false;
1047
+ manual.textContent = `manual path: ${data.manual}`;
1048
+ }
1049
+ btn.disabled = false;
1050
+ }
1051
+ } else if (btn.dataset.action === 'notes') {
1052
+ const panel = $('#notes-panel');
1053
+ if (!panel) return;
1054
+ if (!panel.hidden) {
1055
+ panel.hidden = true;
1056
+ return;
1057
+ }
1058
+ panel.hidden = false;
1059
+ $('#notes-md').textContent = 'Loading…';
1060
+ try {
1061
+ const res = await fetch(`/api/runs/${id}/handoff`);
1062
+ const text = await res.text();
1063
+ $('#notes-md').innerHTML = text.trim()
1064
+ ? renderMarkdown(text)
1065
+ : '<p class="dim">(no notes yet — the handoff file is seeded when the task starts)</p>';
1066
+ } catch (err) {
1067
+ $('#notes-md').textContent = `✗ ${err.message}`;
1068
+ }
1069
+ } else if (btn.dataset.action === 'remove-worktree') {
1070
+ const res = await fetch(`/api/runs/${id}/remove-worktree`, { method: 'POST' });
1071
+ if (!res.ok) {
1072
+ const data = await res.json().catch(() => ({}));
1073
+ alertBar(data.error ?? 'cannot remove worktree');
1074
+ } else {
1075
+ alertBar('Worktree removed.');
1076
+ }
227
1077
  } else if (btn.dataset.action === 'jump-bottom') {
228
1078
  state.autoScroll = true;
229
1079
  const log = $('#log');
@@ -240,6 +1090,212 @@ function bindUi() {
240
1090
  });
241
1091
  }
242
1092
 
1093
+ // ---- chain-from-prompt (spec 008) --------------------------------------------
1094
+
1095
+ function bindPlanPanel() {
1096
+ $('#plan-btn').addEventListener('click', () => void planTask());
1097
+
1098
+ const panel = $('#plan-panel');
1099
+ panel.addEventListener('click', (e) => {
1100
+ if (!state.plan) return;
1101
+ const rm = e.target.closest('[data-plan-remove]');
1102
+ if (rm) {
1103
+ state.plan.steps.splice(Number(rm.dataset.planRemove), 1);
1104
+ renderPlan();
1105
+ return;
1106
+ }
1107
+ const btn = e.target.closest('button[data-plan-action]');
1108
+ if (!btn) return;
1109
+ if (btn.dataset.planAction === 'discard') discardPlan();
1110
+ else if (btn.dataset.planAction === 'start') void startPlannedRun(btn);
1111
+ else if (btn.dataset.planAction === 'save') void savePlanAsChain(btn);
1112
+ });
1113
+
1114
+ // Reorder by drag (HTML5 draggable — no libraries).
1115
+ panel.addEventListener('dragstart', (e) => {
1116
+ const step = e.target.closest('.plan-step');
1117
+ if (!step) return;
1118
+ state.planDragIdx = Number(step.dataset.idx);
1119
+ e.dataTransfer.effectAllowed = 'move';
1120
+ });
1121
+ panel.addEventListener('dragover', (e) => {
1122
+ const step = e.target.closest('.plan-step');
1123
+ if (!step || state.planDragIdx === null) return;
1124
+ e.preventDefault();
1125
+ e.dataTransfer.dropEffect = 'move';
1126
+ step.classList.add('drag-over');
1127
+ });
1128
+ panel.addEventListener('dragleave', (e) => {
1129
+ e.target.closest('.plan-step')?.classList.remove('drag-over');
1130
+ });
1131
+ panel.addEventListener('drop', (e) => {
1132
+ const step = e.target.closest('.plan-step');
1133
+ if (!step || state.planDragIdx === null || !state.plan) return;
1134
+ e.preventDefault();
1135
+ const from = state.planDragIdx;
1136
+ const to = Number(step.dataset.idx);
1137
+ state.planDragIdx = null;
1138
+ if (from === to) return;
1139
+ const [moved] = state.plan.steps.splice(from, 1);
1140
+ state.plan.steps.splice(to, 0, moved);
1141
+ renderPlan();
1142
+ });
1143
+ panel.addEventListener('dragend', () => {
1144
+ state.planDragIdx = null;
1145
+ for (const el of panel.querySelectorAll('.drag-over')) el.classList.remove('drag-over');
1146
+ });
1147
+ }
1148
+
1149
+ async function planTask() {
1150
+ const form = $('#new-task');
1151
+ const task = form.task.value.trim();
1152
+ const errorBox = $('#form-error');
1153
+ errorBox.hidden = true;
1154
+ if (!task) {
1155
+ form.task.focus();
1156
+ return;
1157
+ }
1158
+ const btn = $('#plan-btn');
1159
+ const original = btn.innerHTML; // keep the star icon — no emoji swap
1160
+ btn.disabled = true;
1161
+ btn.classList.add('busy');
1162
+ btn.innerHTML =
1163
+ '<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linejoin="round"><path d="M12 3l2 5.5L19.5 10 14 12l-2 5.5L10 12l-5.5-2L10 8.5 12 3z"/></svg>Planning…';
1164
+ try {
1165
+ const res = await fetch('/api/plan', {
1166
+ method: 'POST',
1167
+ headers: { 'content-type': 'application/json' },
1168
+ body: JSON.stringify({ task }),
1169
+ });
1170
+ const data = await res.json();
1171
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
1172
+ state.plan = { task, steps: data.steps, rationale: data.rationale, fallback: data.fallback };
1173
+ renderPlan();
1174
+ } catch (err) {
1175
+ errorBox.textContent = err.message;
1176
+ errorBox.hidden = false;
1177
+ } finally {
1178
+ btn.disabled = false;
1179
+ btn.classList.remove('busy');
1180
+ btn.innerHTML = original;
1181
+ }
1182
+ }
1183
+
1184
+ function oneLine(s, max = 70) {
1185
+ const first = String(s ?? '').split('\n')[0] ?? '';
1186
+ return first.length > max ? `${first.slice(0, max - 1)}…` : first;
1187
+ }
1188
+
1189
+ /* The proposed chain renders as an overlay over the main window (feedback
1190
+ 2026-07-11: the sidebar was too cramped — step names and prompts were
1191
+ truncated to uselessness). Same bindings as before: #plan-panel, .plan-step,
1192
+ data-plan-* — only the placement and roominess changed. */
1193
+ function renderPlan() {
1194
+ const overlay = $('#plan-overlay');
1195
+ const panel = $('#plan-panel');
1196
+ if (!state.plan) {
1197
+ overlay.hidden = true;
1198
+ panel.innerHTML = '';
1199
+ return;
1200
+ }
1201
+ const { task, steps, rationale, fallback } = state.plan;
1202
+ overlay.hidden = false;
1203
+ panel.innerHTML = `
1204
+ <div class="plan-head">
1205
+ <div style="min-width:0">
1206
+ <div class="panel-label" style="margin-bottom:5px">Proposed chain</div>
1207
+ <div class="plan-task" title="${esc(task)}">${esc(oneLine(task, 120))}</div>
1208
+ </div>
1209
+ <button type="button" class="plan-close" data-plan-action="discard" title="Discard the plan">×</button>
1210
+ </div>
1211
+ ${fallback ? '<div class="plan-note">planner unavailable — single-step plan</div>' : ''}
1212
+ ${rationale ? `<div class="plan-rationale">${esc(rationale)}</div>` : ''}
1213
+ <div class="plan-steps">
1214
+ ${steps
1215
+ .map(
1216
+ (s, i) => `
1217
+ <div class="plan-step" draggable="true" data-idx="${i}">
1218
+ <span class="grip" title="Drag to reorder">≡</span>
1219
+ <span class="num">${String(i + 1).padStart(2, '0')}</span>
1220
+ <div class="plan-step-main">
1221
+ <div class="row1">
1222
+ <span class="name">${esc(s.name ?? s.id)}</span>
1223
+ ${s.skill ? `<span class="plan-badge skill" title="skill">${esc(s.skill)}</span>` : ''}
1224
+ ${s.command ? '<span class="plan-badge check">check</span>' : ''}
1225
+ </div>
1226
+ <div class="hint">${esc(s.command ?? s.prompt ?? '')}</div>
1227
+ </div>
1228
+ <button type="button" class="plan-remove" data-plan-remove="${i}" title="Remove step">✕</button>
1229
+ </div>`,
1230
+ )
1231
+ .join('') || '<div class="dim">(no steps left — discard and plan again)</div>'}
1232
+ </div>
1233
+ <div class="plan-actions">
1234
+ <button type="button" class="btn-dark" data-plan-action="start" ${steps.length ? '' : 'disabled'}>▶ Start</button>
1235
+ <button type="button" class="btn-ghost" data-plan-action="save" ${steps.length ? '' : 'disabled'}>Save as chain</button>
1236
+ <button type="button" class="btn-ghost" data-plan-action="discard">Discard</button>
1237
+ </div>`;
1238
+ }
1239
+
1240
+ function discardPlan() {
1241
+ state.plan = null;
1242
+ state.planDragIdx = null;
1243
+ renderPlan();
1244
+ }
1245
+
1246
+ async function startPlannedRun(btn) {
1247
+ const form = $('#new-task');
1248
+ const task = form.task.value.trim() || state.plan.task;
1249
+ btn.disabled = true;
1250
+ try {
1251
+ const res = await fetch('/api/runs', {
1252
+ method: 'POST',
1253
+ headers: { 'content-type': 'application/json' },
1254
+ body: JSON.stringify({
1255
+ task,
1256
+ steps: state.plan.steps,
1257
+ model: state.taskModel || undefined,
1258
+ variants: state.variants > 1 ? state.variants : undefined,
1259
+ images: state.taskImages.length
1260
+ ? state.taskImages.map((i) => ({ mediaType: i.mediaType, data: i.data }))
1261
+ : undefined,
1262
+ }),
1263
+ });
1264
+ const data = await res.json();
1265
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
1266
+ form.task.value = '';
1267
+ state.taskImages = [];
1268
+ renderTaskThumbs();
1269
+ discardPlan();
1270
+ handleStarted(data);
1271
+ } catch (err) {
1272
+ alertBar(err.message);
1273
+ btn.disabled = false;
1274
+ }
1275
+ }
1276
+
1277
+ async function savePlanAsChain(btn) {
1278
+ const name = prompt('Chain name:');
1279
+ if (!name || !name.trim()) return;
1280
+ btn.disabled = true;
1281
+ try {
1282
+ const res = await fetch('/api/workflows', {
1283
+ method: 'POST',
1284
+ headers: { 'content-type': 'application/json' },
1285
+ body: JSON.stringify({ name: name.trim(), steps: state.plan.steps }),
1286
+ });
1287
+ const data = await res.json();
1288
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
1289
+ alertBar(`Saved — ${String(data.path).split('/').pop()}`);
1290
+ const workflowsRes = await getJson('/api/workflows');
1291
+ setWorkflowOptions(workflowsRes.workflows);
1292
+ } catch (err) {
1293
+ alertBar(err.message);
1294
+ } finally {
1295
+ btn.disabled = false;
1296
+ }
1297
+ }
1298
+
243
1299
  // ---- live-session message bar ------------------------------------------------
244
1300
 
245
1301
  function bindMessageBar(runId) {
@@ -291,11 +1347,12 @@ function bindMessageBar(runId) {
291
1347
  });
292
1348
  }
293
1349
 
294
- async function addImage(file) {
295
- if (state.pendingImages.length >= 4) return;
1350
+ /* File {mediaType, data, preview}, or null when oversized. Shared by the
1351
+ live-session bar and the new-task form. */
1352
+ async function readImageFile(file) {
296
1353
  if (file.size > 5 * 1024 * 1024) {
297
1354
  alertBar('Image too large (max 5 MB)');
298
- return;
1355
+ return null;
299
1356
  }
300
1357
  const buf = await file.arrayBuffer();
301
1358
  let binary = '';
@@ -304,14 +1361,30 @@ async function addImage(file) {
304
1361
  binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
305
1362
  }
306
1363
  const data = btoa(binary);
307
- state.pendingImages.push({ mediaType: file.type, data, preview: `data:${file.type};base64,${data}` });
1364
+ return { mediaType: file.type, data, preview: `data:${file.type};base64,${data}` };
1365
+ }
1366
+
1367
+ async function addImage(file) {
1368
+ if (state.pendingImages.length >= 4) return;
1369
+ const img = await readImageFile(file);
1370
+ if (!img) return;
1371
+ state.pendingImages.push(img);
308
1372
  renderThumbs();
309
1373
  }
310
1374
 
311
- function renderThumbs() {
312
- const box = $('#msg-thumbs');
1375
+ function renderTaskThumbs() {
1376
+ const box = $('#task-thumbs');
313
1377
  if (!box) return;
314
- box.hidden = state.pendingImages.length === 0;
1378
+ box.hidden = state.taskImages.length === 0;
1379
+ box.innerHTML = state.taskImages
1380
+ .map((img, idx) => `<span class="thumb" data-idx="${idx}" title="Click to remove"><img src="${img.preview}"></span>`)
1381
+ .join('');
1382
+ }
1383
+
1384
+ function renderThumbs() {
1385
+ const box = $('#msg-thumbs');
1386
+ if (!box) return;
1387
+ box.hidden = state.pendingImages.length === 0;
315
1388
  box.innerHTML = state.pendingImages
316
1389
  .map((img, idx) => `<span class="thumb" data-idx="${idx}" title="Click to remove"><img src="${img.preview}"></span>`)
317
1390
  .join('');
@@ -340,6 +1413,23 @@ async function sendMessage(runId, text, images) {
340
1413
  }
341
1414
  }
342
1415
 
1416
+ function openLightbox(url, name) {
1417
+ closeLightbox();
1418
+ const el = document.createElement('div');
1419
+ el.id = 'lightbox';
1420
+ el.innerHTML = `
1421
+ <div class="lb-inner">
1422
+ <img src="${esc(url)}" alt="${esc(name ?? '')}">
1423
+ <div class="lb-name">${esc(name ?? '')} — click anywhere to close</div>
1424
+ </div>`;
1425
+ el.addEventListener('click', closeLightbox);
1426
+ document.body.appendChild(el);
1427
+ }
1428
+
1429
+ function closeLightbox() {
1430
+ $('#lightbox')?.remove();
1431
+ }
1432
+
343
1433
  function alertBar(message) {
344
1434
  const existing = $('#toast');
345
1435
  if (existing) existing.remove();
@@ -352,6 +1442,16 @@ function alertBar(message) {
352
1442
 
353
1443
  // ---- run list --------------------------------------------------------------
354
1444
 
1445
+ /* POST /api/runs answers with one run (×1) or {runs: [...]} (variants). */
1446
+ function handleStarted(data) {
1447
+ const runs = Array.isArray(data.runs) ? data.runs : [data];
1448
+ for (const run of runs) state.runs.set(run.id, run);
1449
+ const first = runs[0];
1450
+ if (first?.groupId) state.expandedGroups.add(first.groupId);
1451
+ renderRunList();
1452
+ if (first) selectRun(first.id);
1453
+ }
1454
+
355
1455
  function sortedRuns() {
356
1456
  // Needs-you-first: waiting/review, then running/queued, then by recency.
357
1457
  return [...state.runs.values()]
@@ -364,6 +1464,14 @@ function sortedRuns() {
364
1464
  });
365
1465
  }
366
1466
 
1467
+ /* Which sidebar group a run (or a variant group's best member) belongs to. */
1468
+ function bucketOf(status) {
1469
+ if (state.listView === 'archived') return 'Archived';
1470
+ if (status === 'waiting' || status === 'review') return 'Needs you';
1471
+ if (status === 'running' || status === 'queued') return 'Working';
1472
+ return 'Recent';
1473
+ }
1474
+
367
1475
  function renderRunList() {
368
1476
  const all = [...state.runs.values()];
369
1477
  const activeCount = all.filter((r) => !r.archived).length;
@@ -371,26 +1479,81 @@ function renderRunList() {
371
1479
  const finishedCount = all.filter(
372
1480
  (r) => !r.archived && ['done', 'failed', 'cancelled'].includes(r.status),
373
1481
  ).length;
374
- const waitingCount = all.filter((r) => !r.archived && r.status === 'waiting').length;
1482
+ const waitingCount = all.filter(
1483
+ (r) => !r.archived && (r.status === 'waiting' || r.status === 'review'),
1484
+ ).length;
375
1485
 
376
1486
  $('#list-tabs').innerHTML = `
377
1487
  <button data-list="active" class="${state.listView === 'active' ? 'active' : ''}">
378
- Active ${activeCount ? `(${activeCount})` : ''}${waitingCount ? ' <span class="dot"></span>' : ''}
1488
+ Active${activeCount ? ` ${activeCount}` : ''}${waitingCount ? ' <span class="dot"></span>' : ''}
379
1489
  </button>
380
1490
  <button data-list="archived" class="${state.listView === 'archived' ? 'active' : ''}">
381
- Archived ${archivedCount ? `(${archivedCount})` : ''}
1491
+ Archived${archivedCount ? ` ${archivedCount}` : ''}
382
1492
  </button>
383
- ${state.listView === 'active' && finishedCount ? `<button data-list="archive-finished" title="Archive all finished runs">📥 ${finishedCount}</button>` : ''}`;
1493
+ ${state.listView === 'active' && finishedCount ? `<button data-list="archive-finished" title="Archive all finished runs"><svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round" style="vertical-align:-1.5px;margin-right:4px"><path d="M4 5h16v4H4zM6 9v10h12V9M9 13h6"/></svg>${finishedCount}</button>` : ''}`;
384
1494
 
385
- $('#run-list').innerHTML = sortedRuns()
386
- .map(
387
- (r) => `
388
- <div class="run-item ${r.id === state.selectedId ? 'selected' : ''}" data-id="${r.id}">
389
- <div class="title" title="${esc(r.task)}">${esc(r.title)}</div>
390
- <div class="meta">${badge(r.status)} ${prBadge(r)} <span>${esc(r.workflow)}</span> <span>${fmtTokens(r.tokensUsed)}</span> ${r.costUsd ? `<span>${fmtCost(r.costUsd)}</span>` : ''} <span>${timeAgo(r.createdAt)}</span></div>
391
- </div>`,
392
- )
393
- .join('');
1495
+ // Variant groups (spec 010): runs sharing a groupId collapse into one
1496
+ // group tile at the position of their best-ranked member; click expands.
1497
+ const runs = sortedRuns();
1498
+ const seenGroups = new Set();
1499
+ const buckets = new Map(); // label -> html[]
1500
+ const push = (label, html) => {
1501
+ if (!buckets.has(label)) buckets.set(label, []);
1502
+ buckets.get(label).push(html);
1503
+ };
1504
+ for (const r of runs) {
1505
+ if (r.groupId) {
1506
+ if (seenGroups.has(r.groupId)) continue;
1507
+ seenGroups.add(r.groupId);
1508
+ const members = runs
1509
+ .filter((m) => m.groupId === r.groupId)
1510
+ .sort((a, b) => (a.variant ?? '').localeCompare(b.variant ?? ''));
1511
+ if (members.length > 1) {
1512
+ push(bucketOf(r.status), groupTileHtml(r.groupId, members));
1513
+ continue;
1514
+ }
1515
+ // A lone survivor (the picked winner) renders like any other run.
1516
+ }
1517
+ push(bucketOf(r.status), runItemHtml(r));
1518
+ }
1519
+ const order = ['Needs you', 'Working', 'Recent', 'Archived'];
1520
+ $('#run-list').innerHTML =
1521
+ order
1522
+ .filter((label) => buckets.has(label))
1523
+ .map((label) => `<div class="group-label">${label}</div>${buckets.get(label).join('')}`)
1524
+ .join('') ||
1525
+ `<div class="dim" style="padding:14px 12px;font-size:12px">${
1526
+ state.listView === 'archived' ? 'Nothing archived yet.' : 'No runs yet — describe a task above.'
1527
+ }</div>`;
1528
+ }
1529
+
1530
+ function runItemHtml(r, variantRow = false) {
1531
+ const timeText =
1532
+ r.status === 'queued' ? `#${queuePosition(r) ?? '·'}` : shortAgo(r.finishedAt ?? r.createdAt);
1533
+ return `
1534
+ <div class="run-item ${variantRow ? 'variant-row' : ''} ${r.id === state.selectedId ? 'selected' : ''}" data-id="${r.id}" title="${esc(r.task)}">
1535
+ <span class="dot ${esc(r.status)}"></span>
1536
+ ${r.variant ? `<span class="time">${esc(r.variant)}</span>` : ''}
1537
+ <span class="title">${esc(variantRow ? groupTitle(r) : r.title)}</span>
1538
+ ${r.pullRequestUrl ? `<a class="time" href="${esc(r.pullRequestUrl)}" target="_blank" rel="noopener" title="open the PR">PR↗</a>` : ''}
1539
+ <span class="time">${esc(timeText)}</span>
1540
+ </div>`;
1541
+ }
1542
+
1543
+ function groupTileHtml(groupId, members) {
1544
+ const first = members[0];
1545
+ const expanded = state.expandedGroups.has(groupId);
1546
+ const allTerminal = members.every((m) => TERMINAL_STATUSES.includes(m.status));
1547
+ return `
1548
+ <div class="run-item group-item ${state.selectedGroupId === groupId ? 'selected' : ''}" data-group="${esc(groupId)}" title="${esc(first.task)}">
1549
+ <span class="time">${expanded ? '▾' : '▸'}</span>
1550
+ <span class="title">${esc(groupTitle(first))}</span>
1551
+ <span class="dots">${members
1552
+ .map((m) => `<span class="dot ${esc(m.status)}" title="${esc(`${m.variant ?? '?'} · ${m.status}`)}"></span>`)
1553
+ .join('')}</span>
1554
+ ${allTerminal ? `<button type="button" class="compare-btn" data-compare="${esc(groupId)}" title="Compare the variants' diffs side by side">⚖</button>` : `<span class="time">${members.length}×</span>`}
1555
+ </div>
1556
+ ${expanded ? members.map((m) => runItemHtml(m, true)).join('') : ''}`;
394
1557
  }
395
1558
 
396
1559
  // ---- run detail ------------------------------------------------------------
@@ -399,6 +1562,7 @@ function selectRun(id) {
399
1562
  const run = state.runs.get(id);
400
1563
  if (!run) return;
401
1564
  state.selectedId = id;
1565
+ state.selectedGroupId = null;
402
1566
  state.lastSeq = 0;
403
1567
  state.autoScroll = true;
404
1568
  if (state.runEs) {
@@ -422,21 +1586,43 @@ function selectRun(id) {
422
1586
  function renderDetailShell(run) {
423
1587
  state.pendingImages = [];
424
1588
  $('#detail').innerHTML = `
425
- <div class="detail-header" id="detail-header"></div>
426
- <div class="steps-rail" id="steps-rail"></div>
1589
+ <div class="detail-head">
1590
+ <div class="meta-line" id="d-meta"></div>
1591
+ <div class="title-row">
1592
+ <h1 id="d-title"></h1>
1593
+ <span id="d-badge"></span>
1594
+ </div>
1595
+ <div class="head-bar">
1596
+ <span class="steps-line" id="d-steps"></span>
1597
+ <div class="spacer"></div>
1598
+ <span id="d-actions" style="display:flex;align-items:center;gap:4px;flex-wrap:wrap"></span>
1599
+ </div>
1600
+ <div id="d-error" class="run-error" hidden></div>
1601
+ <div id="d-resume" class="resume-hint" hidden></div>
1602
+ </div>
1603
+ <div id="review-panel" class="detail-panel" hidden></div>
1604
+ <div id="diff-panel" class="detail-panel" hidden><div class="inner"><div class="panel-label">What this task changed</div><div id="diff-body"></div></div></div>
1605
+ <div id="notes-panel" class="detail-panel" hidden><div class="inner"><div class="panel-label">Handoff notes</div><div id="notes-md" class="md"></div></div></div>
427
1606
  <div class="log-wrap">
428
- <div id="log"></div>
1607
+ <div id="log"><div class="log-inner" id="log-inner"></div></div>
429
1608
  <button id="jump-bottom" data-action="jump-bottom" hidden>↓ jump to bottom</button>
430
1609
  </div>
431
- <form id="msg-form">
432
- <div id="msg-thumbs" hidden></div>
433
- <div class="msg-row">
434
- <button type="button" id="msg-attach" title="Attach an image">📎</button>
435
- <textarea id="msg-text" rows="1" placeholder="Message the agent… (Enter to send, ⌘V to paste a screenshot)"></textarea>
436
- <button type="submit" id="msg-send" class="primary">➤</button>
437
- </div>
438
- <input type="file" id="msg-file" accept="image/*" multiple hidden>
439
- </form>`;
1610
+ <div class="composer-wrap">
1611
+ <div id="waiting-note" hidden><span class="pulse-dot"></span>The agent is paused, waiting for your reply</div>
1612
+ <form id="msg-form">
1613
+ <div id="msg-thumbs" hidden></div>
1614
+ <div class="msg-row">
1615
+ <textarea id="msg-text" rows="1" placeholder="Message the agent…"></textarea>
1616
+ <button type="button" id="msg-attach" title="Attach an image (or paste a screenshot)">
1617
+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M20 11l-8 8a5 5 0 01-7-7l8-8a3.4 3.4 0 015 5l-8 8a1.7 1.7 0 01-2.4-2.4l7-7"/></svg>
1618
+ </button>
1619
+ <button type="submit" id="msg-send" title="Send (Enter)">
1620
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2"><path d="M12 19V5M6 11l6-6 6 6"/></svg>
1621
+ </button>
1622
+ </div>
1623
+ <input type="file" id="msg-file" accept="image/*" multiple hidden>
1624
+ </form>
1625
+ </div>`;
440
1626
  bindMessageBar(run.id);
441
1627
  updateDetail(run);
442
1628
  $('#log').addEventListener('scroll', () => {
@@ -447,24 +1633,76 @@ function renderDetailShell(run) {
447
1633
  });
448
1634
  }
449
1635
 
1636
+ const STEP_MARK = { done: '✓', running: '●', waiting: '●', review: '●', failed: '✗' };
1637
+
450
1638
  function updateDetail(run) {
451
1639
  state.runs.set(run.id, run);
452
1640
  const active = run.status === 'running' || run.status === 'queued' || run.status === 'waiting';
453
1641
  const lastSession = [...run.steps].reverse().find((s) => s.sessionId)?.sessionId;
454
- $('#detail-header').innerHTML = `
455
- ${badge(run.status)}
456
- <h2 title="${esc(run.task)}">${esc(run.title)}</h2>
457
- ${run.status === 'waiting' ? '<button data-action="finish">✓ Finish</button>' : ''}
458
- ${!active && lastSession ? '<button data-action="continue">▶ Continue</button><button data-action="open-cli">⌨ Open in terminal</button>' : ''}
459
- ${!active ? `<button data-action="archive" title="${run.archived ? 'Unarchive' : 'Archive'}">${run.archived ? '📤' : '📥'}</button>` : ''}
1642
+ const resumeCmd = run.worktreePath
1643
+ ? `cd ${run.worktreePath} && claude --resume ${lastSession}`
1644
+ : `claude --resume ${lastSession}`;
1645
+
1646
+ const metaParts = [
1647
+ esc(run.workflow),
1648
+ esc(fmtTokens(run.tokensUsed)),
1649
+ run.costUsd ? esc(fmtCost(run.costUsd)) : null,
1650
+ `started ${esc(timeAgo(run.startedAt ?? run.createdAt))}`,
1651
+ run.finishedAt ? `finished ${esc(timeAgo(run.finishedAt))}` : null,
1652
+ run.model ? `model ${esc(run.model)}` : null,
1653
+ run.branch ? esc(run.branch) : null,
1654
+ prLink(run) || null,
1655
+ ].filter(Boolean);
1656
+ $('#d-meta').innerHTML = metaParts.map((p) => `<span>${p}</span>`).join('<span>·</span>');
1657
+
1658
+ $('#d-title').textContent = run.title;
1659
+ $('#d-title').title = run.task;
1660
+ $('#d-badge').innerHTML = statusPill(run);
1661
+
1662
+ $('#d-steps').innerHTML = run.steps
1663
+ .map((s) => {
1664
+ const mark = STEP_MARK[s.status] ?? '○';
1665
+ const label = `${mark} ${esc(s.name)}${s.iterations > 1 ? ` ×${s.iterations}` : ''}`;
1666
+ const tip = `${s.kind} · ${s.status} · ${fmtTokens(s.tokensUsed)}${s.error ? `\n${s.error}` : ''}${s.sessionId ? `\nsession: ${s.sessionId}` : ''}`;
1667
+ return `<span title="${esc(tip)}">${label}</span>`;
1668
+ })
1669
+ .join('<span style="opacity:.5">&nbsp;&nbsp;→&nbsp;&nbsp;</span>');
1670
+
1671
+ $('#d-actions').innerHTML = `
1672
+ ${run.status === 'waiting' || run.status === 'review' ? `<button class="btn-dark" data-action="finish" title="${run.status === 'review' ? 'Accept the changes without a PR' : 'Close the session'}">${BI.check}Finish</button>` : ''}
1673
+ ${!active && lastSession ? `<button class="btn-text" data-action="continue">${BI.play}Continue</button><button class="btn-text" data-action="open-cli" title="Take over the session in a real terminal">${BI.terminal}Terminal</button>` : ''}
1674
+ ${run.worktreePath ? `<button class="btn-text" data-action="diff" title="What this task changed (worktree vs base)">${BI.diff}Diff</button>` : ''}
1675
+ <button class="btn-text" data-action="notes" title="Handoff notes — what the agent did and what's left">${BI.notes}Notes</button>
1676
+ ${run.archived && run.worktreePath ? `<button class="btn-text" data-action="remove-worktree" title="Remove the task worktree and its branch">${BI.folder}Remove worktree</button>` : ''}
1677
+ ${!active ? `<button class="btn-text" data-action="archive" title="${run.archived ? 'Unarchive' : 'Archive'}">${BI.archive}${run.archived ? 'Unarchive' : 'Archive'}</button>` : ''}
460
1678
  ${active
461
- ? '<button data-action="cancel" class="danger">■ Cancel</button>'
462
- : '<button data-action="delete" class="danger">🗑 Delete</button>'}
463
- <div class="sub">
464
- ${esc(run.workflow)} ${prBadge(run)} · ${fmtTokens(run.tokensUsed)}${run.costUsd ? ` · ${fmtCost(run.costUsd)}` : ''} · started ${timeAgo(run.startedAt ?? run.createdAt)}${run.finishedAt ? ` · finished ${timeAgo(run.finishedAt)}` : ''}${run.model ? ` · model ${esc(run.model)}` : ''}
465
- ${run.error ? `<br>✗ ${esc(run.error)}` : ''}
466
- ${!active && lastSession ? `<br>take over interactively: claude --resume ${esc(lastSession)}` : ''}
467
- </div>`;
1679
+ ? `<button class="btn-text danger" data-action="cancel">${BI.stop}Cancel</button>`
1680
+ : `<button class="btn-text danger" data-action="delete">${BI.trash}Delete</button>`}`;
1681
+
1682
+ const errBox = $('#d-error');
1683
+ errBox.hidden = !run.error;
1684
+ if (run.error) errBox.textContent = `✗ ${run.error}`;
1685
+ const resumeBox = $('#d-resume');
1686
+ const showResume = !active && lastSession;
1687
+ resumeBox.hidden = !showResume;
1688
+ if (showResume) resumeBox.textContent = `take over interactively: ${resumeCmd}`;
1689
+
1690
+ // Review gate (spec 009): the panel lives while the run rests at `review`;
1691
+ // it (re)loads the diff on each entry into review and clears on exit, so a
1692
+ // send-back round always comes back with a fresh diff.
1693
+ const reviewPanel = $('#review-panel');
1694
+ if (reviewPanel) {
1695
+ const inReview = run.status === 'review';
1696
+ reviewPanel.hidden = !inReview;
1697
+ if (inReview && !reviewPanel.dataset.loaded) {
1698
+ reviewPanel.dataset.loaded = '1';
1699
+ void renderReviewPanel(run.id);
1700
+ } else if (!inReview && reviewPanel.dataset.loaded) {
1701
+ delete reviewPanel.dataset.loaded;
1702
+ reviewPanel.innerHTML = '';
1703
+ }
1704
+ }
1705
+
468
1706
  const msgForm = $('#msg-form');
469
1707
  if (msgForm) {
470
1708
  const sessionOpen = run.status === 'running' || run.status === 'waiting';
@@ -474,71 +1712,266 @@ function updateDetail(run) {
474
1712
  $('#msg-attach').disabled = !sessionOpen;
475
1713
  $('#msg-text').placeholder = sessionOpen
476
1714
  ? run.status === 'waiting'
477
- ? 'The agent is waiting for you… (Enter to send)'
478
- : 'Message the agent… (Enter to send, ⌘V to paste a screenshot)'
479
- : 'Session closed.';
1715
+ ? 'Reply to the agent… (Enter to send, ⌘V pastes a screenshot)'
1716
+ : 'Message the agent… (Enter to send, ⌘V pastes a screenshot)'
1717
+ : 'Session closed — Continue to reopen.';
1718
+ $('#waiting-note').hidden = run.status !== 'waiting';
1719
+ }
1720
+ }
1721
+
1722
+ /* Review gate panel (spec 009): the full diff on top, then a notes field with
1723
+ exactly two buttons — "Send back" (feedback into the same session) and
1724
+ "Draft PR". The third exit, "✓ Finish" (accept without a PR), sits in the
1725
+ detail header. */
1726
+ async function renderReviewPanel(runId) {
1727
+ const panel = $('#review-panel');
1728
+ if (!panel) return;
1729
+ // A PR the agent already opened itself (skill-driven `gh pr create`, spotted
1730
+ // in the transcript) replaces the Draft PR button — a second click would
1731
+ // open a duplicate PR.
1732
+ const prUrl = state.runs.get(runId)?.pullRequestUrl;
1733
+ panel.innerHTML = `
1734
+ <div class="inner">
1735
+ <div class="panel-label">Changes ready for review</div>
1736
+ <div id="review-diff"><div class="dim">Loading diff…</div></div>
1737
+ <textarea id="review-notes" rows="2" placeholder="Notes for the agent — what should change?"></textarea>
1738
+ <div class="review-buttons">
1739
+ <button type="button" class="btn-ghost" data-action="send-back" title="Send the notes back into the agent's session">↩ Send back</button>
1740
+ ${
1741
+ prUrl
1742
+ ? `<a class="btn-dark" style="text-decoration:none" href="${esc(prUrl)}" target="_blank" rel="noopener" title="The agent already opened this PR">PR ↗ open on GitHub</a>`
1743
+ : '<button type="button" class="btn-dark" data-action="draft-pr" title="Push the branch and open a draft PR">Draft PR</button>'
1744
+ }
1745
+ </div>
1746
+ <div id="review-manual" class="dim mono" hidden></div>
1747
+ </div>`;
1748
+ try {
1749
+ const res = await fetch(`/api/runs/${runId}/diff`);
1750
+ const text = await res.text();
1751
+ const box = $('#review-diff');
1752
+ if (box) box.innerHTML = renderDiff(text);
1753
+ } catch (err) {
1754
+ const box = $('#review-diff');
1755
+ if (box) box.textContent = `✗ ${err.message}`;
1756
+ }
1757
+ }
1758
+
1759
+ // ---- variant compare view (spec 010) ----------------------------------------
1760
+
1761
+ /* "⚖ Compare": columns per variant — status, cost, `git diff --stat`, the
1762
+ first Progress-log lines — each with a "Pick this one" button; full diffs
1763
+ collapse under the columns (renderDiff from spec 009, reused). */
1764
+ async function selectGroup(groupId) {
1765
+ state.selectedGroupId = groupId;
1766
+ state.selectedId = null;
1767
+ if (state.runEs) {
1768
+ state.runEs.close();
1769
+ state.runEs = null;
1770
+ }
1771
+ showRunsView();
1772
+ renderRunList();
1773
+ const detail = $('#detail');
1774
+ detail.innerHTML = '<div class="empty">Loading variants…</div>';
1775
+ let data;
1776
+ try {
1777
+ data = await getJson(`/api/groups/${groupId}`);
1778
+ } catch (err) {
1779
+ detail.innerHTML = `<div class="empty">✗ ${esc(err.message)}</div>`;
1780
+ return;
1781
+ }
1782
+ if (state.selectedGroupId !== groupId) return; // user moved on meanwhile
1783
+ renderCompareView(data.runs);
1784
+ }
1785
+
1786
+ function renderCompareView(variants) {
1787
+ const title = variants.length ? groupTitle(variants[0]) : '';
1788
+ $('#detail').innerHTML = `
1789
+ <div class="compare-view"><div class="inner">
1790
+ <div class="compare-head">
1791
+ <h1 title="${esc(title)}">⚖ ${esc(title)}</h1>
1792
+ <span class="dim">${variants.length} variants — pick the diff you want to keep; the others are archived and their worktrees removed</span>
1793
+ </div>
1794
+ <div class="compare-cols">
1795
+ ${variants
1796
+ .map(
1797
+ (v) => `
1798
+ <div class="compare-col">
1799
+ <div class="col-head"><span class="variant-letter">${esc(v.variant)}</span> ${statusPill(v)}</div>
1800
+ <div class="col-meta">${fmtTokens(v.tokensUsed)}${v.costUsd ? ` · ${fmtCost(v.costUsd)}` : ''}</div>
1801
+ <pre class="col-stat">${esc(v.diffStat || '(no changes)')}</pre>
1802
+ <pre class="col-handoff">${esc(v.handoffExcerpt || '(no progress notes)')}</pre>
1803
+ <button type="button" class="btn-dark" data-pick="${esc(v.id)}">✔ Pick this one</button>
1804
+ </div>`,
1805
+ )
1806
+ .join('')}
1807
+ </div>
1808
+ <div class="compare-diffs">
1809
+ ${variants
1810
+ .map(
1811
+ (v) => `
1812
+ <details class="compare-diff">
1813
+ <summary>Variant ${esc(v.variant)} — full diff</summary>
1814
+ <div class="diff-body" data-group-diff="${esc(v.id)}"><div class="dim">Loading…</div></div>
1815
+ </details>`,
1816
+ )
1817
+ .join('')}
1818
+ </div>
1819
+ </div></div>`;
1820
+ // Full diffs (max 3) via the existing per-run endpoint.
1821
+ for (const v of variants) {
1822
+ void fetch(`/api/runs/${v.id}/diff`)
1823
+ .then((r) => r.text())
1824
+ .then((text) => {
1825
+ const box = document.querySelector(`[data-group-diff="${v.id}"]`);
1826
+ if (box) box.innerHTML = renderDiff(text);
1827
+ })
1828
+ .catch(() => undefined);
1829
+ }
1830
+ }
1831
+
1832
+ /* "Pick this one" → the winner rests at `review` (the spec-009 gate takes it
1833
+ from there); the losers are archived and their worktrees removed. */
1834
+ async function pickVariant(btn) {
1835
+ const groupId = state.selectedGroupId;
1836
+ if (!groupId) return;
1837
+ btn.disabled = true;
1838
+ try {
1839
+ const res = await fetch(`/api/groups/${groupId}/pick`, {
1840
+ method: 'POST',
1841
+ headers: { 'content-type': 'application/json' },
1842
+ body: JSON.stringify({ runId: btn.dataset.pick }),
1843
+ });
1844
+ const data = await res.json();
1845
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
1846
+ if (data.winner) state.runs.set(data.winner.id, data.winner);
1847
+ state.expandedGroups.delete(groupId);
1848
+ renderRunList();
1849
+ if (data.winner) selectRun(data.winner.id); // lands on the review gate
1850
+ } catch (err) {
1851
+ alertBar(err.message);
1852
+ btn.disabled = false;
480
1853
  }
481
- $('#steps-rail').innerHTML = run.steps
482
- .map(
483
- (s) => `
484
- <div class="step-card" title="${esc(s.error ?? '')}${s.sessionId ? `\nsession: ${esc(s.sessionId)}` : ''}">
485
- ${badge(s.status)}
486
- <span class="name">${esc(s.name)}</span>
487
- <span class="dim">${s.kind}${s.iterations > 1 ? ` ×${s.iterations}` : ''}</span>
488
- <span class="tok">${fmtTokens(s.tokensUsed)}</span>
489
- </div>`,
490
- )
491
- .join('');
1854
+ }
1855
+
1856
+ // ---- transcript ------------------------------------------------------------
1857
+
1858
+ /* The most telling single argument of a tool call — a command, a path, a
1859
+ pattern — shown inside the tool chip. */
1860
+ /* Design language for tool chips: a human verb, not the raw tool name —
1861
+ "✓ Ran `npm test`", "✓ Accepted edits to `src/x.ts`". Unknown tools keep
1862
+ their name as the verb. */
1863
+ const TOOL_VERB = {
1864
+ Bash: 'Ran',
1865
+ Read: 'Read',
1866
+ Edit: 'Accepted edits to',
1867
+ MultiEdit: 'Accepted edits to',
1868
+ NotebookEdit: 'Accepted edits to',
1869
+ Write: 'Created',
1870
+ Grep: 'Searched',
1871
+ Glob: 'Searched',
1872
+ LS: 'Listed',
1873
+ WebFetch: 'Fetched',
1874
+ WebSearch: 'Searched the web for',
1875
+ TodoWrite: 'Updated the todo list',
1876
+ Task: 'Delegated',
1877
+ };
1878
+
1879
+ function toolVerb(tool) {
1880
+ return TOOL_VERB[tool] ?? tool;
1881
+ }
1882
+
1883
+ function toolArg(input) {
1884
+ if (input == null) return null;
1885
+ if (typeof input === 'string') return input.trim() || null;
1886
+ if (typeof input !== 'object') return String(input);
1887
+ for (const key of ['command', 'file_path', 'path', 'pattern', 'url', 'query', 'name', 'description', 'prompt']) {
1888
+ const v = input[key];
1889
+ if (typeof v === 'string' && v.trim()) return v.trim();
1890
+ }
1891
+ // No recognizable primary argument — the design never shows raw JSON blobs.
1892
+ return null;
492
1893
  }
493
1894
 
494
1895
  function appendLog(evt) {
1896
+ const inner = $('#log-inner');
495
1897
  const log = $('#log');
496
- if (!log) return;
1898
+ if (!inner || !log) return;
497
1899
  const el = document.createElement('div');
498
- el.className = `ev ${evt.type}${evt.isError ? ' error' : ''}`;
499
1900
 
500
1901
  switch (evt.type) {
501
1902
  case 'text':
502
- el.textContent = evt.text ?? '';
1903
+ // Agents speak markdown — render it (bold, code, lists) instead of
1904
+ // showing raw ** and ##.
1905
+ el.className = 'ev text md';
1906
+ el.innerHTML = renderMarkdown(evt.text ?? '');
503
1907
  break;
504
1908
  case 'tool-call': {
505
- const input = JSON.stringify(evt.input ?? {}, null, 2);
506
- const preview = input.length > 100 ? `${input.slice(0, 97).replaceAll('\n', ' ')}…` : input.replaceAll('\n', ' ');
507
- el.innerHTML =
508
- input.length > 100
509
- ? `→ ${esc(evt.tool)} <details><summary>${esc(preview)}</summary><pre>${esc(input)}</pre></details>`
510
- : `→ ${esc(evt.tool)} ${esc(preview)}`;
1909
+ el.className = 'ev tool';
1910
+ const arg = toolArg(evt.input);
1911
+ el.innerHTML = `<span class="ok">✓</span><span>${esc(toolVerb(evt.tool))}</span>${
1912
+ arg ? `<span class="arg">${esc(oneLine(arg, 64))}</span>` : ''
1913
+ }`;
1914
+ el.title = arg && arg.length > 64 ? arg.slice(0, 1000) : evt.tool;
511
1915
  break;
512
1916
  }
513
1917
  case 'tool-result': {
514
1918
  const result = String(evt.result ?? '');
515
- const first = result.split('\n')[0] ?? '';
516
- el.innerHTML =
517
- result.length > first.length
518
- ? `← <details><summary>${esc(first.slice(0, 140))}${result.length > 140 ? '…' : ''}</summary><pre>${esc(result.slice(0, 10_000))}</pre></details>`
519
- : `← ${esc(first)}`;
1919
+ const first = (result.split('\n')[0] ?? '').slice(0, 140);
1920
+ const hasMore = result.length > first.length;
1921
+ el.className = `ev result${evt.isError ? ' error' : ''}`;
1922
+ el.innerHTML = hasMore
1923
+ ? `<details><summary><span class="lead-in">↳</span><span class="head">${esc(first)}${result.length > 140 ? '…' : ''}</span><span class="show">show</span></summary><pre>${esc(result.slice(0, 10_000))}</pre></details>`
1924
+ : `<span class="ev tool" style="margin:0"><span class="lead-in" style="color:var(--text3);font-size:11px">↳</span><span>${esc(first)}</span></span>`;
1925
+ break;
1926
+ }
1927
+ case 'check-output': {
1928
+ el.className = 'ev check';
1929
+ const ok = evt.exitCode === 0;
1930
+ el.innerHTML = `
1931
+ <div class="check-head">
1932
+ <span class="lbl">Command</span>
1933
+ <code>${esc(evt.command ?? evt.stepId ?? 'check')}</code>
1934
+ <span class="check-pill ${ok ? 'pass' : 'fail'}">${ok ? 'passed' : `failed (exit ${esc(String(evt.exitCode))})`}</span>
1935
+ </div>
1936
+ <pre>${esc(String(evt.text ?? ''))}</pre>`;
520
1937
  break;
521
1938
  }
522
- case 'check-output':
523
- el.textContent = `${evt.text ?? ''}\n(exit ${evt.exitCode})`;
1939
+ case 'image':
1940
+ el.className = 'ev image-ev';
1941
+ el.innerHTML = `
1942
+ <div class="img-card" data-lightbox="${esc(evt.url)}" data-name="${esc(evt.name)}" title="Click to zoom">
1943
+ <img src="${esc(evt.url)}" alt="${esc(evt.name)}" loading="lazy">
1944
+ <div class="img-foot">
1945
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="var(--text3)" stroke-width="1.8" stroke-linejoin="round"><path d="M4 5h16v14H4z"/><path d="M4 15l5-5 4 4 3-3 4 4"/><circle cx="9.5" cy="9.5" r="1.1"/></svg>
1946
+ <span class="nm">${esc(evt.name)}</span>
1947
+ <span class="zm">click to zoom</span>
1948
+ </div>
1949
+ </div>`;
524
1950
  break;
525
1951
  case 'step-start':
526
- el.textContent = `▸ ${evt.name}${evt.iteration > 1 ? ` (attempt ${evt.iteration})` : ''}`;
1952
+ el.className = 'ev step';
1953
+ el.innerHTML = `<span class="step-label">${esc(evt.name ?? evt.stepId ?? 'step')}${evt.iteration > 1 ? ` · attempt ${esc(String(evt.iteration))}` : ''}</span><div class="rule"></div>`;
527
1954
  break;
528
1955
  case 'step-end':
1956
+ // Successful step ends are already told by the steps rail and the next
1957
+ // step divider — the design keeps the transcript free of this noise.
1958
+ if (evt.status !== 'failed') return;
529
1959
  el.className = 'ev note';
530
- el.textContent = `step ${evt.stepId}: ${evt.status}${evt.error ? ` — ${evt.error}` : ''}`;
1960
+ el.textContent = `step ${evt.stepId}: failed${evt.error ? ` — ${evt.error}` : ''}`;
531
1961
  break;
532
1962
  case 'note':
533
1963
  case 'lifecycle':
1964
+ el.className = 'ev note';
534
1965
  el.textContent = `· ${evt.message ?? ''}`;
535
1966
  break;
536
1967
  case 'user-message': {
1968
+ el.className = 'ev user';
537
1969
  const imgs = evt.imageCount > 0 ? ` [${evt.imageCount} image${evt.imageCount > 1 ? 's' : ''}]` : '';
538
- el.textContent = `you: ${evt.text ?? ''}${imgs}`;
1970
+ el.innerHTML = `<div class="bubble">${esc(`${evt.text ?? ''}${imgs}`)}</div>`;
539
1971
  break;
540
1972
  }
541
1973
  case 'error':
1974
+ el.className = 'ev err';
542
1975
  el.textContent = `✗ ${evt.message ?? ''}`;
543
1976
  break;
544
1977
  case 'token-usage':
@@ -548,84 +1981,1318 @@ function appendLog(evt) {
548
1981
  case 'done':
549
1982
  return;
550
1983
  default:
1984
+ el.className = 'ev note';
551
1985
  el.textContent = JSON.stringify(evt);
552
1986
  }
553
1987
 
554
- log.appendChild(el);
1988
+ inner.appendChild(el);
555
1989
  if (state.autoScroll) log.scrollTop = log.scrollHeight;
556
1990
  }
557
1991
 
1992
+ // ---- inbox view (spec 007) -----------------------------------------------------
1993
+
1994
+ /* Entries already turned into a task (startedTaskId) are hidden — they stay
1995
+ in todos.json as an audit trail. */
1996
+ function visibleTodos() {
1997
+ return state.todos.filter((t) => !t.startedTaskId);
1998
+ }
1999
+
2000
+ function renderInboxBadge() {
2001
+ const badgeEl = $('#inbox-badge');
2002
+ if (!badgeEl) return;
2003
+ const count = visibleTodos().length;
2004
+ badgeEl.textContent = count;
2005
+ badgeEl.hidden = count === 0;
2006
+ }
2007
+
2008
+ function showRunsView() {
2009
+ const btn = $('#tabs button[data-view="runs"]');
2010
+ if (btn && !btn.classList.contains('active')) btn.click();
2011
+ }
2012
+
2013
+ function renderInbox() {
2014
+ const view = $('#view-inbox');
2015
+ const todos = visibleTodos();
2016
+ view.innerHTML = `
2017
+ <div class="page">
2018
+ <h1>Inbox</h1>
2019
+ <p class="lead">Follow-ups agents suggested when they finished a task.</p>
2020
+ ${
2021
+ todos.length
2022
+ ? todos
2023
+ .map((t) => {
2024
+ const source = t.taskId
2025
+ ? state.runs.has(t.taskId)
2026
+ ? `<a href="#" data-goto-run="${esc(t.taskId)}">source task</a>`
2027
+ : '<span class="gone">source task deleted</span>'
2028
+ : '';
2029
+ const pr = t.prUrl
2030
+ ? `<a href="${esc(t.prUrl)}" target="_blank" rel="noopener">PR</a>`
2031
+ : '';
2032
+ return `
2033
+ <div class="todo-card" data-id="${esc(t.id)}">
2034
+ <div class="todo-main">
2035
+ <div class="summary">${esc(t.summary)}</div>
2036
+ <div class="meta">
2037
+ ${t.ts ? `<span>${esc(timeAgo(t.ts))}</span>` : ''}
2038
+ ${t.action ? `<span>${esc(t.action)}</span>` : ''}
2039
+ ${source} ${pr}
2040
+ ${t.suggestedSkill ? `<span>skill: ${esc(t.suggestedSkill)}</span>` : ''}
2041
+ </div>
2042
+ </div>
2043
+ <button class="btn-dark" data-todo-action="start" title="Start a task from this follow-up">▶ Run</button>
2044
+ <button class="btn-text" data-todo-action="remove" title="Check off (remove)">Dismiss</button>
2045
+ </div>`;
2046
+ })
2047
+ .join('')
2048
+ : '<div class="dim" style="padding:16px 0">Inbox empty — agents drop follow-up suggestions here when they finish a task.</div>'
2049
+ }
2050
+ </div>`;
2051
+ }
2052
+
2053
+ // ---- GitHub view -------------------------------------------------------------
2054
+
2055
+ const GH_ISSUE_ICON = 'M12 3a9 9 0 100 18 9 9 0 000-18zM12 10.5a1.5 1.5 0 100 3 1.5 1.5 0 000-3z';
2056
+ const GH_PR_ICON =
2057
+ 'M7 8.5v7M7 3.5a2.5 2.5 0 100 5 2.5 2.5 0 000-5zM7 15.5a2.5 2.5 0 100 5 2.5 2.5 0 000-5zM17 15.5a2.5 2.5 0 100 5 2.5 2.5 0 000-5zM17 15v-4a3 3 0 00-3-3h-2.5';
2058
+
2059
+ function bindGithubView() {
2060
+ const view = $('#view-github');
2061
+ view.addEventListener('click', async (e) => {
2062
+ const refresh = e.target.closest('[data-gh-refresh]');
2063
+ if (refresh) {
2064
+ await loadGithub(true);
2065
+ return;
2066
+ }
2067
+ const tab = e.target.closest('button[data-gh-view]');
2068
+ if (tab) {
2069
+ state.ghView = tab.dataset.ghView;
2070
+ state.ghSel = null;
2071
+ renderGithub();
2072
+ return;
2073
+ }
2074
+ const row = e.target.closest('.gh-row');
2075
+ if (row) {
2076
+ state.ghSel = row.dataset.url;
2077
+ renderGithub();
2078
+ return;
2079
+ }
2080
+ const wf = e.target.closest('button[data-gh-workflow]');
2081
+ if (wf) {
2082
+ // Click the selected chip again to deselect — no workflow means the
2083
+ // run uses the toggled skills (or quick-task).
2084
+ state.ghWorkflow = state.ghWorkflow === wf.dataset.ghWorkflow ? null : wf.dataset.ghWorkflow;
2085
+ renderGithub();
2086
+ return;
2087
+ }
2088
+ const sk = e.target.closest('button[data-gh-skill]');
2089
+ if (sk) {
2090
+ const name = sk.dataset.ghSkill;
2091
+ if (state.ghSkills.has(name)) state.ghSkills.delete(name);
2092
+ else state.ghSkills.add(name);
2093
+ renderGithub();
2094
+ return;
2095
+ }
2096
+ const viewRun = e.target.closest('button[data-gh-view-run]');
2097
+ if (viewRun) {
2098
+ showRunsView();
2099
+ selectRun(viewRun.dataset.ghViewRun);
2100
+ return;
2101
+ }
2102
+ const runBtn = e.target.closest('button[data-gh-run]');
2103
+ if (runBtn) {
2104
+ await runOnGithub(runBtn);
2105
+ return;
2106
+ }
2107
+ });
2108
+
2109
+ // Live filter over the skill chips — re-renders only the chip box so the
2110
+ // input keeps focus (and the page keeps its scroll).
2111
+ view.addEventListener('input', (e) => {
2112
+ if (e.target.id !== 'gh-skill-filter') return;
2113
+ state.ghSkillQuery = e.target.value;
2114
+ const box = $('#gh-skill-chips');
2115
+ if (box) box.innerHTML = ghSkillChipsHtml();
2116
+ });
2117
+
2118
+ // Drag an issue/PR row into the task box — it prefills the same prompt
2119
+ // "Run agent on this issue" uses; skill/workflow you pick in the form.
2120
+ view.addEventListener('dragstart', (e) => {
2121
+ const row = e.target.closest('.gh-row[data-url]');
2122
+ if (!row) return;
2123
+ const item = ghItems().find((i) => i.url === row.dataset.url);
2124
+ if (!item) return;
2125
+ try {
2126
+ e.dataTransfer.setData('text/plain', ghTaskPrompt(item));
2127
+ e.dataTransfer.effectAllowed = 'copy';
2128
+ } catch {
2129
+ // older engines — drag just won't carry the prompt
2130
+ }
2131
+ });
2132
+ }
2133
+
2134
+ /* Two-shot load (feedback 2026-07-11 — the 30-item gh default hid the rest):
2135
+ the first fast fetch paints the tab, then a background "everything open"
2136
+ fetch (limit 1000) replaces it and fixes the counts. */
2137
+ async function loadGithub(refresh = false) {
2138
+ const view = $('#view-github');
2139
+ if (!state.gh || refresh) {
2140
+ if (!state.gh) view.innerHTML = '<div class="gh-unavailable">Loading GitHub…</div>';
2141
+ try {
2142
+ // Skill chips ride along — same catalog as the Skills tab.
2143
+ const [gh, skills] = await Promise.all([
2144
+ getJson(`/api/github${refresh ? '?refresh=1' : ''}`),
2145
+ state.skillsList ? Promise.resolve(state.skillsList) : getJson('/api/skills').catch(() => []),
2146
+ ]);
2147
+ state.gh = gh;
2148
+ state.skillsList = skills;
2149
+ state.ghFull = false;
2150
+ } catch (err) {
2151
+ view.innerHTML = `<div class="gh-unavailable">✗ ${esc(err.message)}</div>`;
2152
+ return;
2153
+ }
2154
+ }
2155
+ renderGithub();
2156
+ if (state.gh?.available && !state.ghFull) void loadGithubFull();
2157
+ }
2158
+
2159
+ async function loadGithubFull() {
2160
+ if (state.ghFullLoading) return;
2161
+ state.ghFullLoading = true;
2162
+ try {
2163
+ const full = await getJson('/api/github?limit=1000');
2164
+ if (full.available) {
2165
+ state.gh = full;
2166
+ state.ghFull = true;
2167
+ renderGithub();
2168
+ }
2169
+ } catch {
2170
+ // the fast batch stays — counts just keep their "+"
2171
+ } finally {
2172
+ state.ghFullLoading = false;
2173
+ }
2174
+ }
2175
+
2176
+ function ghItems() {
2177
+ if (!state.gh) return [];
2178
+ return state.ghView === 'issues' ? state.gh.issues : state.gh.prs;
2179
+ }
2180
+
2181
+ function renderGithub() {
2182
+ const view = $('#view-github');
2183
+ const gh = state.gh;
2184
+ if (!gh) return;
2185
+ if (!gh.available) {
2186
+ view.innerHTML = `
2187
+ <div class="gh-unavailable">
2188
+ <div style="font-family:var(--serif);font-size:21px;color:var(--text);margin-bottom:10px">GitHub</div>
2189
+ GitHub is unavailable here — ${esc(gh.reason ?? 'unknown reason')}.<br><br>
2190
+ The tab needs the <span class="mono">gh</span> CLI, logged in (<span class="mono">gh auth login</span>),
2191
+ and a repo with a GitHub remote. Everything else in cezar works without it.
2192
+ <div style="margin-top:14px"><button class="btn-ghost" data-gh-refresh>⟳ Try again</button></div>
2193
+ </div>`;
2194
+ return;
2195
+ }
2196
+
2197
+ const items = ghItems();
2198
+ let sel = items.find((i) => i.url === state.ghSel) ?? items[0] ?? null;
2199
+ if (sel) state.ghSel = sel.url;
2200
+
2201
+ const rows = items.length
2202
+ ? items
2203
+ .map((i) => {
2204
+ const queuedRun = state.ghQueued.get(i.url);
2205
+ return `
2206
+ <div class="gh-row ${sel && i.url === sel.url ? 'selected' : ''}" data-url="${esc(i.url)}" draggable="true" title="Drag into the task box to prefill a task">
2207
+ <div class="row1">
2208
+ <svg viewBox="0 0 24 24" style="stroke:${i.kind === 'issue' ? 'var(--green)' : 'var(--accent)'}"><path d="${i.kind === 'issue' ? GH_ISSUE_ICON : GH_PR_ICON}"/></svg>
2209
+ <span class="t">${esc(i.title)}</span>
2210
+ </div>
2211
+ <div class="row2">
2212
+ <span>#${i.number}</span><span>${esc(i.author)}</span><span>${esc(shortAgo(i.createdAt))}</span>
2213
+ ${queuedRun ? '<span class="queued-flag">↗ run queued</span>' : ''}
2214
+ </div>
2215
+ </div>`;
2216
+ })
2217
+ .join('')
2218
+ : `<div class="dim" style="padding:12px">No open ${state.ghView === 'issues' ? 'issues' : 'pull requests'}.</div>`;
2219
+
2220
+ const detail = sel ? ghDetailHtml(sel) : '<div class="empty">Nothing selected.</div>';
2221
+
2222
+ // A full re-render must not jump the scroll (feedback 2026-07-11: toggling
2223
+ // a skill chip yanked the detail back to the top).
2224
+ const rowsScroll = view.querySelector('.split-rows')?.scrollTop ?? 0;
2225
+ const detailScroll = view.querySelector('.split-detail')?.scrollTop ?? 0;
2226
+
2227
+ // Until the background full fetch lands, a count at the fast-batch cap is
2228
+ // really "30 of who knows" — say so.
2229
+ const countLabel = (n) => `${n}${!state.ghFull && n >= 30 ? '+' : ''}`;
2230
+
2231
+ view.innerHTML = `
2232
+ <div class="split">
2233
+ <div class="split-list">
2234
+ <div class="split-head">
2235
+ <div class="head-row">
2236
+ <h1>GitHub</h1>
2237
+ <span class="mono dim" style="font-size:10.5px">${esc(gh.repo ?? '')}</span>
2238
+ <button class="head-note" data-gh-refresh style="border:none;background:transparent;cursor:pointer" title="Refresh from GitHub">
2239
+ <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round"><path d="M20 11a8 8 0 10-2.3 5.7M20 11V5m0 6h-6"/></svg>
2240
+ synced ${esc(gh.syncedAt ? shortAgo(gh.syncedAt) : '?')} ago${state.ghFullLoading ? ' · loading all…' : ''}
2241
+ </button>
2242
+ </div>
2243
+ <div class="sub-tabs">
2244
+ <button data-gh-view="issues" class="${state.ghView === 'issues' ? 'active' : ''}">Issues · ${countLabel(gh.issues.length)}</button>
2245
+ <button data-gh-view="prs" class="${state.ghView === 'prs' ? 'active' : ''}">Pull requests · ${countLabel(gh.prs.length)}</button>
2246
+ </div>
2247
+ </div>
2248
+ <div class="split-rows">${rows}</div>
2249
+ </div>
2250
+ <div class="split-detail">${detail}</div>
2251
+ </div>`;
2252
+
2253
+ const rowsEl = view.querySelector('.split-rows');
2254
+ if (rowsEl) rowsEl.scrollTop = rowsScroll;
2255
+ const detailEl = view.querySelector('.split-detail');
2256
+ if (detailEl) detailEl.scrollTop = detailScroll;
2257
+ }
2258
+
2259
+ function ghDetailHtml(item) {
2260
+ const kindWord = item.kind === 'pr' ? 'pull request' : 'issue';
2261
+ const diffStat =
2262
+ item.kind === 'pr' && (item.additions || item.deletions) ? ` · +${item.additions} −${item.deletions}` : '';
2263
+ const checks = item.checks
2264
+ ? `<span class="gh-checks ${esc(item.checks)}">${
2265
+ item.checks === 'passing' ? '✓ checks passing' : item.checks === 'failing' ? '✗ checks failing' : '○ checks pending'
2266
+ }</span>`
2267
+ : '';
2268
+ const skills = (state.skillsList ?? []).map((s) => s.name);
2269
+ const queuedRun = state.ghQueued.get(item.url);
2270
+ return `
2271
+ <div class="inner">
2272
+ <div class="mono dim" style="font-size:10.5px">#${item.number} · ${kindWord} · opened by ${esc(item.author)} · ${esc(shortAgo(item.createdAt))} ago${item.comments ? ` · ${item.comments} comments` : ''}${diffStat} · <a href="${esc(item.url)}" target="_blank" rel="noopener">open on GitHub ↗</a></div>
2273
+ <h1 style="margin-top:8px">${esc(item.title)}</h1>
2274
+ <div style="display:flex;align-items:center;gap:7px;margin-top:12px;flex-wrap:wrap">
2275
+ ${item.labels.map((l) => `<span class="gh-label">${esc(l)}</span>`).join('')}
2276
+ ${checks}
2277
+ </div>
2278
+ <div class="gh-body md">${item.body ? renderMarkdown(item.body) : '<p class="dim">(no description)</p>'}</div>
2279
+ <div class="gh-hand">
2280
+ <div class="hand-label">
2281
+ <svg viewBox="0 0 24 24"><path d="M13 2L4.5 13.5h5.5L9 22l8.5-11.5H12L13 2z"/></svg>
2282
+ Hand this to the agent
2283
+ </div>
2284
+ <div class="hand-row">
2285
+ <span class="k" style="padding-top:0;align-self:center">workflow</span>
2286
+ <div class="chips">
2287
+ ${state.workflows
2288
+ .map(
2289
+ (w) =>
2290
+ `<button class="chip-toggle ${state.ghWorkflow === w.name ? 'on' : ''}" data-gh-workflow="${esc(w.name)}" title="${esc(w.description ?? '')}${state.ghWorkflow === w.name ? ' — click again to deselect' : ''}">${esc(w.name)}</button>`,
2291
+ )
2292
+ .join('')}
2293
+ </div>
2294
+ </div>
2295
+ ${
2296
+ skills.length
2297
+ ? `<div class="hand-row">
2298
+ <span class="k">skills</span>
2299
+ <div style="flex:1;min-width:0">
2300
+ ${
2301
+ skills.length > 10
2302
+ ? `<input id="gh-skill-filter" class="filter-input" style="width:min(260px,100%);margin:0 0 8px" placeholder="Filter skills…" value="${esc(state.ghSkillQuery)}">`
2303
+ : ''
2304
+ }
2305
+ <div class="chips" id="gh-skill-chips">${ghSkillChipsHtml()}</div>
2306
+ </div>
2307
+ </div>`
2308
+ : ''
2309
+ }
2310
+ <div class="go-row">
2311
+ <button class="btn-dark" data-gh-run="${esc(item.url)}">▶ Run agent on this ${item.kind === 'pr' ? 'PR' : 'issue'}</button>
2312
+ ${
2313
+ queuedRun
2314
+ ? `<span class="queued-ok">✓ queued</span><button class="btn-text" data-gh-view-run="${esc(queuedRun)}">View in Runs →</button>`
2315
+ : ''
2316
+ }
2317
+ </div>
2318
+ </div>
2319
+ </div>`;
2320
+ }
2321
+
2322
+ /* Skill chips, filterable — toggled-on chips always stay visible so the
2323
+ filter can't hide your selection. */
2324
+ function ghSkillChipsHtml() {
2325
+ const q = state.ghSkillQuery.trim().toLowerCase();
2326
+ const names = (state.skillsList ?? []).map((s) => s.name);
2327
+ const shown = names.filter((n) => state.ghSkills.has(n) || !q || n.toLowerCase().includes(q));
2328
+ if (!shown.length) return '<span class="dim" style="font-size:11.5px">No skills match.</span>';
2329
+ return shown
2330
+ .map(
2331
+ (name) =>
2332
+ `<button class="chip-toggle ${state.ghSkills.has(name) ? 'on' : ''}" data-gh-skill="${esc(name)}">${esc(name)}</button>`,
2333
+ )
2334
+ .join('');
2335
+ }
2336
+
2337
+ /* The prompt handed to the agent — shared by "Run agent on this …" and the
2338
+ drag-into-the-task-box path. */
2339
+ function ghTaskPrompt(item, skillNames = []) {
2340
+ let task = `${item.kind === 'pr' ? 'Address GitHub pull request' : 'Fix GitHub issue'} #${item.number}: ${item.title}\n\n${item.url}`;
2341
+ if (item.body?.trim()) task += `\n\n---\n\n${item.body.trim()}`;
2342
+ if (skillNames.length) task += `\n\nUse these skills where relevant: ${skillNames.join(', ')}.`;
2343
+ return task;
2344
+ }
2345
+
2346
+ async function runOnGithub(btn) {
2347
+ const item = ghItems().find((i) => i.url === btn.dataset.ghRun);
2348
+ if (!item) return;
2349
+ const skills = [...state.ghSkills].filter((name) => (state.skillsList ?? []).some((s) => s.name === name));
2350
+ // Workflow chip set → that workflow (skills ride along as a prompt hint).
2351
+ // No workflow but skills toggled → the skills ARE the chain (spec 008).
2352
+ // Nothing selected → quick-task.
2353
+ let body;
2354
+ if (state.ghWorkflow) {
2355
+ body = { workflow: state.ghWorkflow, task: ghTaskPrompt(item, skills) };
2356
+ } else if (skills.length) {
2357
+ const steps = [];
2358
+ for (const name of skills.slice(0, 8)) steps.push(wbSkillStep(name, steps));
2359
+ body = { steps, task: ghTaskPrompt(item) };
2360
+ } else {
2361
+ body = { workflow: 'quick-task', task: ghTaskPrompt(item) };
2362
+ }
2363
+ btn.disabled = true;
2364
+ try {
2365
+ const res = await fetch('/api/runs', {
2366
+ method: 'POST',
2367
+ headers: { 'content-type': 'application/json' },
2368
+ body: JSON.stringify(body),
2369
+ });
2370
+ const data = await res.json();
2371
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
2372
+ state.runs.set(data.id, data);
2373
+ state.ghQueued.set(item.url, data.id);
2374
+ state.lastGhRun = data.id;
2375
+ renderRunList();
2376
+ renderGithub();
2377
+ } catch (err) {
2378
+ alertBar(err.message);
2379
+ btn.disabled = false;
2380
+ }
2381
+ }
2382
+
558
2383
  // ---- repo view ---------------------------------------------------------------
559
2384
 
2385
+ function statusClass(status) {
2386
+ if (/A|\?/.test(status)) return 'added';
2387
+ if (/D/.test(status)) return 'deleted';
2388
+ return '';
2389
+ }
2390
+
560
2391
  async function loadRepo() {
561
2392
  const view = $('#view-repo');
562
- view.innerHTML = '<div class="dim">Loading…</div>';
2393
+ view.innerHTML = '<div class="page dim">Loading…</div>';
563
2394
  try {
564
2395
  const [repo, diff] = await Promise.all([
565
2396
  getJson('/api/repo'),
566
2397
  fetch('/api/repo/diff').then((r) => r.text()),
567
2398
  ]);
568
2399
  if (!repo.info) {
569
- view.innerHTML = '<div class="panel">Not a git repository.</div>';
2400
+ view.innerHTML = '<div class="page"><h1>Repository</h1><p class="lead">Not a git repository — tasks run in place, one at a time.</p></div>';
570
2401
  return;
571
2402
  }
572
2403
  view.innerHTML = `
573
- <div class="panel">
574
- <h3>Repository</h3>
575
- <div class="mono">${esc(repo.info.root)} · <b>${esc(repo.info.branch)}</b>${repo.info.remote ? ` · ${esc(repo.info.remote)}` : ''}</div>
576
- </div>
577
- <div class="panel">
578
- <h3>Working tree (${repo.status.length} changed)</h3>
579
- ${repo.status.length
580
- ? `<table>${repo.status.map((s) => `<tr><td class="mono dim">${esc(s.status)}</td><td class="mono">${esc(s.path)}</td></tr>`).join('')}</table>`
581
- : '<div class="dim">clean</div>'}
582
- </div>
583
- <div class="panel">
584
- <h3>Diff vs HEAD</h3>
585
- ${diff.trim() ? `<pre>${esc(diff)}</pre>` : '<div class="dim">no changes</div>'}
586
- </div>
587
- <div class="panel">
588
- <h3>Recent commits</h3>
589
- <table>${repo.log.map((l) => `<tr><td class="mono dim">${esc(l.hash)}</td><td>${esc(l.subject)}</td><td class="dim">${esc(l.author)}</td><td class="dim">${esc(l.when)}</td></tr>`).join('')}</table>
2404
+ <div class="page">
2405
+ <h1>Repository</h1>
2406
+ <p class="lead mono" style="font-size:12px">${esc(repo.info.root)} · ${esc(repo.info.branch)}${repo.info.remote ? ` · ${esc(repo.info.remote)}` : ''}</p>
2407
+
2408
+ <div class="section-label">Agent base branch</div>
2409
+ <div class="base-branch-row">
2410
+ <select id="base-branch">
2411
+ <option value="" ${repo.baseBranch ? '' : 'selected'}>current checkout (${esc(repo.info.branch)})</option>
2412
+ ${(repo.branches ?? [])
2413
+ .map((b) => `<option value="${esc(b)}" ${repo.baseBranch === b ? 'selected' : ''}>${esc(b)}</option>`)
2414
+ .join('')}
2415
+ </select>
2416
+ <span class="dim" style="font-size:11.5px;line-height:1.5">Task worktrees fork from this branch and draft PRs target it. Saved to <span class="mono">.ai/cezar/config.json</span>.</span>
2417
+ </div>
2418
+
2419
+ <div class="section-label">Working tree · ${repo.status.length ? `${repo.status.length} changed` : 'clean'}</div>
2420
+ ${
2421
+ repo.status.length
2422
+ ? repo.status
2423
+ .map(
2424
+ (s) =>
2425
+ `<div class="repo-file"><span class="st ${statusClass(s.status)}">${esc(s.status)}</span><span class="p">${esc(s.path)}</span></div>`,
2426
+ )
2427
+ .join('')
2428
+ : '<div class="dim" style="font-size:12.5px">Nothing modified.</div>'
2429
+ }
2430
+ ${
2431
+ diff.trim()
2432
+ ? `<details class="repo-diff"><summary>Diff vs HEAD</summary><div class="diff-wrap">${renderDiff(diff)}</div></details>`
2433
+ : ''
2434
+ }
2435
+
2436
+ <div class="section-label">Recent commits</div>
2437
+ ${repo.log
2438
+ .map(
2439
+ (l) => `
2440
+ <div class="commit-row clickable" data-sha="${esc(l.hash)}" title="Show this commit">
2441
+ <svg class="chev" viewBox="0 0 24 24"><path d="M9 6l6 6-6 6"/></svg>
2442
+ <span class="hash">${esc(l.hash)}</span><span class="subj">${esc(l.subject)}</span><span class="when" title="${esc(l.author)}">${esc(l.when)}</span>
2443
+ </div>
2444
+ <div class="commit-diff" data-diff-for="${esc(l.hash)}" hidden></div>`,
2445
+ )
2446
+ .join('')}
590
2447
  </div>`;
2448
+ view.dataset.ghBase = githubBaseUrl(repo.info.remote) ?? '';
591
2449
  } catch (err) {
592
- view.innerHTML = `<div class="panel">✗ ${esc(err.message)}</div>`;
2450
+ view.innerHTML = `<div class="page">✗ ${esc(err.message)}</div>`;
593
2451
  }
594
2452
  }
595
2453
 
2454
+ /* `git@github.com:o/r.git` / `https://github.com/o/r(.git)` → https://github.com/o/r */
2455
+ function githubBaseUrl(remote) {
2456
+ const m = /github\.com[:/]([^/\s]+)\/([^/\s]+?)(?:\.git)?$/.exec(remote ?? '');
2457
+ return m ? `https://github.com/${m[1]}/${m[2]}` : null;
2458
+ }
2459
+
2460
+ /* Click a commit row → expand its message + patch inline (spec: Repo view).
2461
+ Bound once; loadRepo re-renders the innerHTML under it. */
2462
+ function bindRepoView() {
2463
+ const view = $('#view-repo');
2464
+
2465
+ // Base-branch picker → PUT /api/config (empty value clears back to "current").
2466
+ view.addEventListener('change', async (e) => {
2467
+ if (e.target.id !== 'base-branch') return;
2468
+ const value = e.target.value || null;
2469
+ try {
2470
+ const res = await fetch('/api/config', {
2471
+ method: 'PUT',
2472
+ headers: { 'content-type': 'application/json' },
2473
+ body: JSON.stringify({ baseBranch: value }),
2474
+ });
2475
+ const data = await res.json().catch(() => ({}));
2476
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
2477
+ alertBar(value ? `New tasks will branch off "${value}" (PRs target it too).` : 'Base branch cleared — tasks follow the current checkout.');
2478
+ } catch (err) {
2479
+ alertBar(err.message);
2480
+ }
2481
+ });
2482
+
2483
+ view.addEventListener('click', async (e) => {
2484
+ if (e.target.closest('a')) return; // the GitHub link inside an expanded diff
2485
+ const row = e.target.closest('.commit-row[data-sha]');
2486
+ if (!row) return;
2487
+ const sha = row.dataset.sha;
2488
+ const box = view.querySelector(`.commit-diff[data-diff-for="${CSS.escape(sha)}"]`);
2489
+ if (!box) return;
2490
+ if (!box.hidden) {
2491
+ box.hidden = true;
2492
+ row.classList.remove('open');
2493
+ return;
2494
+ }
2495
+ row.classList.add('open');
2496
+ box.hidden = false;
2497
+ if (!box.dataset.loaded) {
2498
+ box.innerHTML = '<div class="dim" style="padding:8px 2px;font-size:12px">Loading…</div>';
2499
+ try {
2500
+ const text = await fetch(`/api/repo/commit/${encodeURIComponent(sha)}`).then((r) => r.text());
2501
+ // `git show` = message + stat, then the patch — split so renderDiff
2502
+ // doesn't swallow the preamble.
2503
+ const at = text.indexOf('\ndiff --git ');
2504
+ const head = at === -1 ? text : text.slice(0, at);
2505
+ const patch = at === -1 ? '' : text.slice(at + 1);
2506
+ const ghBase = view.dataset.ghBase;
2507
+ box.innerHTML = `
2508
+ ${ghBase ? `<a class="commit-gh" href="${esc(ghBase)}/commit/${esc(sha)}" target="_blank" rel="noopener">View on GitHub ↗</a>` : ''}
2509
+ <pre class="commit-head">${esc(head.trim())}</pre>
2510
+ ${patch ? `<div class="diff-wrap">${renderDiff(patch)}</div>` : ''}`;
2511
+ box.dataset.loaded = '1';
2512
+ } catch (err) {
2513
+ box.innerHTML = `<div class="error-text">✗ ${esc(err.message)}</div>`;
2514
+ }
2515
+ }
2516
+ });
2517
+ }
2518
+
596
2519
  // ---- skills view ---------------------------------------------------------------
597
2520
 
598
- async function loadSkills() {
2521
+ const SKILL_ICON = 'M12 3l2 5.5L19.5 10 14 12l-2 5.5L10 12l-5.5-2L10 8.5 12 3z';
2522
+
2523
+ function bindSkillsView() {
599
2524
  const view = $('#view-skills');
600
- view.innerHTML = '<div class="dim">Loading…</div>';
601
- try {
602
- const skills = await getJson('/api/skills');
603
- if (!skills.length) {
604
- view.innerHTML = `
605
- <div class="panel">
606
- <h3>Skills</h3>
607
- <div>No skills yet. Drop Markdown files into <span class="mono">.ai/skills/</span> or <span class="mono">.ai/cezar/skills/</span> —
608
- optional frontmatter: <span class="mono">name</span>, <span class="mono">description</span>.
609
- Reference one from a workflow step via <span class="mono">skill: &lt;name&gt;</span>.</div>
610
- </div>`;
2525
+ view.addEventListener('click', (e) => {
2526
+ if (e.target.closest('#skills-refresh')) {
2527
+ void loadSkills(true);
611
2528
  return;
612
2529
  }
613
- view.innerHTML = skills
614
- .map(
615
- (s) => `
616
- <div class="panel skill-card">
617
- <h3>${esc(s.name)} <span class="dim">(${esc(s.source)})</span></h3>
618
- ${s.description ? `<div>${esc(s.description)}</div>` : ''}
619
- <div class="path mono dim">${esc(s.path)}</div>
620
- <details><summary class="dim">show body</summary><pre>${esc(s.body)}</pre></details>
621
- </div>`,
622
- )
623
- .join('');
2530
+ const row = e.target.closest('.skill-row');
2531
+ if (row) {
2532
+ state.skillSel = row.dataset.skill;
2533
+ renderSkills();
2534
+ return;
2535
+ }
2536
+ });
2537
+ // Filter without re-rendering the input (it would lose focus).
2538
+ view.addEventListener('input', (e) => {
2539
+ if (e.target.id !== 'skill-filter') return;
2540
+ state.skillQuery = e.target.value;
2541
+ const rows = $('#skill-rows');
2542
+ if (rows) rows.innerHTML = skillRowsHtml();
2543
+ });
2544
+ }
2545
+
2546
+ async function loadSkills(refresh = false) {
2547
+ const view = $('#view-skills');
2548
+ if (!state.skillsList || refresh) {
2549
+ if (!state.skillsList) view.innerHTML = '<div class="gh-unavailable">Loading…</div>';
2550
+ try {
2551
+ state.skillsList = refresh
2552
+ ? await fetch('/api/skills/refresh', { method: 'POST' }).then((r) => {
2553
+ if (!r.ok) throw new Error(`refresh → ${r.status}`);
2554
+ return r.json();
2555
+ })
2556
+ : await getJson('/api/skills');
2557
+ if (refresh) alertBar('Team skills refreshed.');
2558
+ renderTaskPills(); // the form's source pill lists the same catalog
2559
+ } catch (err) {
2560
+ view.innerHTML = `<div class="gh-unavailable">✗ ${esc(err.message)}</div>`;
2561
+ return;
2562
+ }
2563
+ }
2564
+ renderSkills();
2565
+ }
2566
+
2567
+ function filteredSkills() {
2568
+ const q = state.skillQuery.trim().toLowerCase();
2569
+ return (state.skillsList ?? []).filter(
2570
+ (s) => !q || s.name.toLowerCase().includes(q) || (s.description ?? '').toLowerCase().includes(q),
2571
+ );
2572
+ }
2573
+
2574
+ function skillRowsHtml() {
2575
+ const skills = filteredSkills();
2576
+ const rows = skills
2577
+ .map(
2578
+ (s) => `
2579
+ <div class="skill-row ${state.skillSel === s.name ? 'selected' : ''}" data-skill="${esc(s.name)}">
2580
+ <div class="row1">
2581
+ <svg viewBox="0 0 24 24"><path d="${SKILL_ICON}"/></svg>
2582
+ <span class="name">${esc(s.name)}</span>
2583
+ <span class="skill-tag ${esc(s.source)}">${esc(s.source)}</span>
2584
+ </div>
2585
+ ${s.description ? `<div class="desc">${esc(s.description)}</div>` : ''}
2586
+ </div>`,
2587
+ )
2588
+ .join('');
2589
+ const empty = state.skillsList?.length
2590
+ ? '<div class="dim" style="padding:12px">(no skills match)</div>'
2591
+ : `<div class="dim" style="padding:12px;font-size:12px;line-height:1.6">No skills yet. Drop Markdown files into <span class="mono">.ai/skills/</span> or <span class="mono">.ai/cezar/skills/</span> — optional frontmatter: <span class="mono">name</span>, <span class="mono">description</span>. Team skills from your skills repo appear here too — try ⟳ Refresh.</div>`;
2592
+ return rows || empty;
2593
+ }
2594
+
2595
+ /* Always-visible entry below the (scrollable) skill list — spec 011 must not
2596
+ drown under a long team catalog. */
2597
+ function bookmarkletRowHtml() {
2598
+ return `
2599
+ <div class="skill-row pinned ${state.skillSel === '__bm' ? 'selected' : ''}" data-skill="__bm">
2600
+ <div class="row1">
2601
+ <svg viewBox="0 0 24 24" style="stroke:var(--accent)"><path d="M13 2L4.5 13.5h5.5L9 22l8.5-11.5H12L13 2z"/></svg>
2602
+ <span class="name">Run from GitHub</span>
2603
+ <span class="skill-tag">bookmarklets</span>
2604
+ </div>
2605
+ <div class="desc">One-click skill launch from any GitHub PR or issue.</div>
2606
+ </div>`;
2607
+ }
2608
+
2609
+ /* Workflows referencing this skill — "fix-and-verify › Verify". */
2610
+ function skillUsedBy(name) {
2611
+ const out = [];
2612
+ for (const w of state.workflows) {
2613
+ for (const s of w.steps ?? []) {
2614
+ if (s.skill === name) out.push(`${w.name} › ${s.name ?? s.id}`);
2615
+ }
2616
+ }
2617
+ return out;
2618
+ }
2619
+
2620
+ function renderSkills() {
2621
+ const view = $('#view-skills');
2622
+ const skills = state.skillsList ?? [];
2623
+ if (state.skillSel !== '__bm' && !skills.some((s) => s.name === state.skillSel)) {
2624
+ state.skillSel = skills[0]?.name ?? '__bm';
2625
+ }
2626
+
2627
+ view.innerHTML = `
2628
+ <div class="split">
2629
+ <div class="split-list">
2630
+ <div class="split-head">
2631
+ <div class="head-row">
2632
+ <h1>Skills</h1>
2633
+ <button id="skills-refresh" class="btn-ghost" style="margin-left:auto;height:27px;font-size:12px" title="git fetch the team skills repos">⟳ Refresh</button>
2634
+ </div>
2635
+ </div>
2636
+ <input id="skill-filter" class="filter-input" placeholder="Filter skills…" value="${esc(state.skillQuery)}">
2637
+ <div class="split-rows" id="skill-rows">${skillRowsHtml()}</div>
2638
+ <div class="list-foot">${bookmarkletRowHtml()}</div>
2639
+ </div>
2640
+ <div class="split-detail" id="skill-detail">${state.skillSel === '__bm' ? bookmarkletShellHtml() : skillDetailHtml()}</div>
2641
+ </div>`;
2642
+
2643
+ if (state.skillSel === '__bm') void bindBookmarklets(skills);
2644
+ }
2645
+
2646
+ function skillDetailHtml() {
2647
+ const skill = (state.skillsList ?? []).find((s) => s.name === state.skillSel);
2648
+ if (!skill) return '<div class="empty">No skill selected.</div>';
2649
+ const usedBy = skillUsedBy(skill.name);
2650
+ return `
2651
+ <div class="inner skill-detail">
2652
+ <div class="title-row">
2653
+ <h1>${esc(skill.name)}</h1>
2654
+ <span class="skill-tag ${esc(skill.source)}">${esc(skill.source)}</span>
2655
+ </div>
2656
+ <div class="path-line">${esc(skill.path)}${skill.team ? ` · from ${esc(skill.team.repo)}` : ''}</div>
2657
+ ${skill.description ? `<div class="desc">${esc(skill.description)}</div>` : ''}
2658
+ <div class="section-label">Used by</div>
2659
+ ${
2660
+ usedBy.length
2661
+ ? usedBy
2662
+ .map(
2663
+ (u) =>
2664
+ `<div class="used-row"><svg viewBox="0 0 24 24"><path d="M4 12h12M12 6l6 6-6 6"/></svg>${esc(u)}</div>`,
2665
+ )
2666
+ .join('')
2667
+ : '<div class="dim" style="font-size:12.5px;padding:6px 0">Not referenced by any workflow yet — quick-task picks it up when the task mentions it.</div>'
2668
+ }
2669
+ <div class="content-head">
2670
+ <span class="section-label">Content</span>
2671
+ <span class="spacer"></span>
2672
+ </div>
2673
+ <pre class="content">${esc(skill.body)}</pre>
2674
+ </div>`;
2675
+ }
2676
+
2677
+ // ---- workflow builder (spec 012) ---------------------------------------------
2678
+
2679
+ /* The Workflows tab: a workflow is (usually) a portable stack of skills the
2680
+ agent applies top to bottom. Drag skills in from the palette, reorder by
2681
+ drag, import/export the YAML, save to `.ai/cezar/workflows/`. Workflows
2682
+ richer than a skill stack (checks, custom prompts — YAML-land) still load,
2683
+ reorder and save; they just serialize in the full `steps:` form instead of
2684
+ the compact `skills:` one. */
2685
+
2686
+ const WB_MAX_STEPS = 8; // the server's save/run step limit
2687
+
2688
+ function wbEmpty() {
2689
+ return {
2690
+ name: 'my-workflow',
2691
+ description: '',
2692
+ steps: [],
2693
+ query: '',
2694
+ importOpen: false,
2695
+ importText: '',
2696
+ importError: '',
2697
+ copied: false,
2698
+ };
2699
+ }
2700
+
2701
+ function wbFrom(w) {
2702
+ return {
2703
+ ...wbEmpty(),
2704
+ name: w.name,
2705
+ description: w.description ?? '',
2706
+ steps: structuredClone(w.steps ?? []),
2707
+ };
2708
+ }
2709
+
2710
+ /* First visit seeds the canvas with the repo's first saved workflow — "open
2711
+ the tab, see your flow". No files yet → an empty canvas + the drop hint. */
2712
+ function openWorkflowsView() {
2713
+ if (!state.wb) {
2714
+ const first = state.workflows.find((w) => w.source === 'file');
2715
+ state.wb = first ? wbFrom(first) : wbEmpty();
2716
+ }
2717
+ renderWorkflowsView();
2718
+ }
2719
+
2720
+ /* Client mirror of the server's skillStackOf(): a pure "apply skill to the
2721
+ task" chain can be written in the compact `skills:` YAML form. */
2722
+ function wbSkillStack(steps) {
2723
+ const skills = [];
2724
+ for (const s of steps) {
2725
+ if (s.command || !s.skill) return null;
2726
+ if (s.prompt !== undefined && s.prompt !== '{{task}}') return null;
2727
+ if (s.name !== undefined && s.name !== s.skill) return null;
2728
+ if (s.model || s.allowedTools || s.bashAllowlist || s.onFail) return null;
2729
+ skills.push(s.skill);
2730
+ }
2731
+ return skills.length ? skills : null;
2732
+ }
2733
+
2734
+ /* Quote only when the plain form would be ambiguous YAML — special characters,
2735
+ or a scalar YAML would read as a boolean/number/null instead of a string.
2736
+ JSON strings are valid YAML double-quoted scalars, so JSON.stringify is the
2737
+ escape hatch. */
2738
+ function yamlScalar(v) {
2739
+ const s = String(v);
2740
+ const plain = /^[A-Za-z0-9._][A-Za-z0-9 ._/-]*$/.test(s) && !s.endsWith(' ');
2741
+ const looksTyped = /^(true|false|yes|no|on|off|null|~)$/i.test(s) || /^[-+.]?\d/.test(s);
2742
+ return plain && !looksTyped ? s : JSON.stringify(s);
2743
+ }
2744
+
2745
+ function yamlBlock(key, text, indent) {
2746
+ const pad = ' '.repeat(indent);
2747
+ if (!text.includes('\n')) return [`${pad}${key}: ${yamlScalar(text)}`];
2748
+ return [`${pad}${key}: |`, ...text.split('\n').map((l) => `${pad} ${l}`)];
2749
+ }
2750
+
2751
+ function wbYamlText() {
2752
+ const wb = state.wb;
2753
+ const lines = [`name: ${yamlScalar(wb.name.trim() || 'my-workflow')}`];
2754
+ if (wb.description.trim()) lines.push(...yamlBlock('description', wb.description.trim(), 0));
2755
+ const stack = wbSkillStack(wb.steps);
2756
+ if (stack) {
2757
+ lines.push('skills:');
2758
+ for (const s of stack) lines.push(` - ${yamlScalar(s)}`);
2759
+ } else if (wb.steps.length) {
2760
+ lines.push('steps:');
2761
+ for (const s of wb.steps) {
2762
+ lines.push(` - id: ${yamlScalar(s.id)}`);
2763
+ if (s.name && s.name !== s.id) lines.push(` name: ${yamlScalar(s.name)}`);
2764
+ if (s.skill) lines.push(` skill: ${yamlScalar(s.skill)}`);
2765
+ if (s.prompt) lines.push(...yamlBlock('prompt', s.prompt, 4));
2766
+ if (s.model) lines.push(` model: ${yamlScalar(s.model)}`);
2767
+ if (s.allowedTools) lines.push(` allowedTools: [${s.allowedTools.map(yamlScalar).join(', ')}]`);
2768
+ if (s.bashAllowlist) lines.push(` bashAllowlist: [${s.bashAllowlist.map(yamlScalar).join(', ')}]`);
2769
+ if (s.command) lines.push(...yamlBlock('command', s.command, 4));
2770
+ if (s.onFail) {
2771
+ lines.push(' onFail:', ` retry: ${yamlScalar(s.onFail.retry)}`, ` max: ${s.onFail.max ?? 2}`);
2772
+ }
2773
+ }
2774
+ } else {
2775
+ lines.push('skills: []');
2776
+ }
2777
+ return `${lines.join('\n')}\n`;
2778
+ }
2779
+
2780
+ function wbCountLabel() {
2781
+ const n = state.wb.steps.length;
2782
+ const noun = wbSkillStack(state.wb.steps) ? 'skill' : 'step';
2783
+ return `${n} ${noun}${n === 1 ? '' : 's'}`;
2784
+ }
2785
+
2786
+ function wbGapHtml(i) {
2787
+ return `<div class="wb-gap" data-gap="${i}"><div class="wb-gap-inner">drop to insert</div></div>`;
2788
+ }
2789
+
2790
+ function wbStepCardHtml(s, i) {
2791
+ const lib = (state.skillsList ?? []).find((k) => k.name === s.skill);
2792
+ let title;
2793
+ let desc;
2794
+ let badge = '';
2795
+ if (s.command) {
2796
+ title = s.name ?? s.id;
2797
+ desc = `$ ${s.command}${s.onFail ? ` — on fail retry from "${s.onFail.retry}" (×${s.onFail.max ?? 2})` : ''}`;
2798
+ badge = '<span class="wb-badge check">check</span>';
2799
+ } else if (s.skill) {
2800
+ title = s.skill;
2801
+ desc = lib
2802
+ ? (lib.description ?? '')
2803
+ : 'Not in this repo or the team skills — the step runs on its plain prompt.';
2804
+ if (!lib) badge = '<span class="wb-badge unknown">unknown</span>';
2805
+ } else {
2806
+ title = s.name ?? s.id;
2807
+ desc = oneLine(s.prompt ?? '', 90);
2808
+ badge = '<span class="wb-badge">prompt</span>';
2809
+ }
2810
+ const icon = s.command
2811
+ ? '<svg class="wb-ic" viewBox="0 0 24 24" style="stroke:var(--green)"><path d="M5 12l5 5 9-11"/></svg>'
2812
+ : `<svg class="wb-ic" viewBox="0 0 24 24"><path d="${SKILL_ICON}"/></svg>`;
2813
+ return `
2814
+ ${wbGapHtml(i)}
2815
+ <div class="wb-step" draggable="true" data-idx="${i}">
2816
+ <svg class="grip" width="10" height="14" viewBox="0 0 10 16"><circle cx="2.5" cy="2.5" r="1.4"/><circle cx="7.5" cy="2.5" r="1.4"/><circle cx="2.5" cy="8" r="1.4"/><circle cx="7.5" cy="8" r="1.4"/><circle cx="2.5" cy="13.5" r="1.4"/><circle cx="7.5" cy="13.5" r="1.4"/></svg>
2817
+ <span class="num mono">${String(i + 1).padStart(2, '0')}</span>
2818
+ ${icon}
2819
+ <div class="wb-step-main">
2820
+ <div class="wb-step-name mono">${esc(title)}</div>
2821
+ ${desc ? `<div class="wb-step-desc">${esc(desc)}</div>` : ''}
2822
+ </div>
2823
+ ${badge}
2824
+ <button type="button" class="wb-remove" data-wb-remove="${i}" title="Remove from flow">×</button>
2825
+ </div>`;
2826
+ }
2827
+
2828
+ function wbStepsHtml() {
2829
+ const steps = state.wb.steps;
2830
+ if (!steps.length) {
2831
+ return '<div class="wb-gap tall" data-gap="0"><div class="wb-gap-inner">drop a skill here — or Import a workflow.yaml</div></div>';
2832
+ }
2833
+ return `${steps.map(wbStepCardHtml).join('')}${wbGapHtml(steps.length)}
2834
+ <div class="wb-flow-note"><svg viewBox="0 0 24 24" width="12" height="12"><path d="M12 5v14M6 13l6 6 6-6"/></svg>runs top to bottom</div>`;
2835
+ }
2836
+
2837
+ function wbPaletteHtml() {
2838
+ const q = state.wb.query.trim().toLowerCase();
2839
+ const inFlow = new Set(state.wb.steps.map((s) => s.skill).filter(Boolean));
2840
+ const skills = (state.skillsList ?? []).filter(
2841
+ (s) => !q || s.name.toLowerCase().includes(q) || (s.description ?? '').toLowerCase().includes(q),
2842
+ );
2843
+ if (!skills.length) {
2844
+ return (state.skillsList ?? []).length
2845
+ ? '<div class="dim" style="font-size:11.5px;padding:4px 2px 8px">No skills match.</div>'
2846
+ : '<div class="dim" style="font-size:11.5px;padding:4px 2px 8px;line-height:1.6">No skills yet — drop Markdown files into <span class="mono">.ai/skills/</span> or <span class="mono">.ai/cezar/skills/</span>.</div>';
2847
+ }
2848
+ return skills
2849
+ .map(
2850
+ (s) => `
2851
+ <div class="wb-skill" draggable="true" data-skill="${esc(s.name)}" title="${esc(s.description ?? '')}">
2852
+ <svg class="wb-ic" viewBox="0 0 24 24"><path d="${SKILL_ICON}"/></svg>
2853
+ <span class="name mono">${esc(s.name)}</span>
2854
+ <span class="wb-skill-right">
2855
+ ${inFlow.has(s.name) ? '<svg class="in-flow" viewBox="0 0 24 24"><path d="M5 12l5 5 9-11"/></svg>' : ''}
2856
+ <svg class="dots" viewBox="0 0 24 24"><circle cx="9" cy="5" r="1.6"/><circle cx="15" cy="5" r="1.6"/><circle cx="9" cy="12" r="1.6"/><circle cx="15" cy="12" r="1.6"/><circle cx="9" cy="19" r="1.6"/><circle cx="15" cy="19" r="1.6"/></svg>
2857
+ </span>
2858
+ </div>`,
2859
+ )
2860
+ .join('');
2861
+ }
2862
+
2863
+ function wbLoadChipsHtml() {
2864
+ const chips = state.workflows
2865
+ .map(
2866
+ (w) =>
2867
+ `<button type="button" class="chip-toggle ${state.wb.name === w.name ? 'on' : ''}" data-wb-load="${esc(w.name)}" title="${esc(w.description ?? '')}">${esc(w.name)}</button>`,
2868
+ )
2869
+ .join('');
2870
+ return `<span class="wb-k">edit</span>${chips}<button type="button" class="chip-toggle" data-wb-load="__new" title="Start an empty workflow">+ new</button>`;
2871
+ }
2872
+
2873
+ function renderWorkflowsView() {
2874
+ const wb = state.wb;
2875
+ $('#view-workflows').innerHTML = `
2876
+ <div class="wb-grid">
2877
+ <div class="wb-main"><div class="wb-inner">
2878
+ <div class="wb-head">
2879
+ <h1>Workflow builder</h1>
2880
+ ${
2881
+ state.workflows.some((w) => w.name === wb.name.trim() && w.source === 'file')
2882
+ ? `<button type="button" class="btn-text danger" data-wb-action="delete" title="Delete the saved workflow file">${BI.trash}Delete</button>`
2883
+ : ''
2884
+ }
2885
+ <button type="button" class="btn-text" data-wb-action="import">⬆ Import</button>
2886
+ <button type="button" class="btn-text" data-wb-action="export">⬇ Export</button>
2887
+ <button type="button" class="btn-dark" data-wb-action="save">✓ Save</button>
2888
+ </div>
2889
+ <div class="wb-meta">
2890
+ <div class="wb-name-pill">
2891
+ <svg viewBox="0 0 24 24"><path d="M4 6h16M4 12h10M4 18h13"/></svg>
2892
+ <input id="wb-name" value="${esc(wb.name)}" spellcheck="false" aria-label="Workflow name">
2893
+ </div>
2894
+ <span class="mono dim" id="wb-count">${wbCountLabel()}</span>
2895
+ </div>
2896
+ <div class="wb-load" id="wb-load">${wbLoadChipsHtml()}</div>
2897
+ <div class="wb-import" ${wb.importOpen ? '' : 'hidden'}>
2898
+ <div class="wb-import-label">Import workflow YAML</div>
2899
+ <textarea id="wb-import-text" rows="6" spellcheck="false" placeholder="name: my-flow&#10;skills:&#10; - test-conventions&#10; - commit-style">${esc(wb.importText)}</textarea>
2900
+ <div class="error-text" style="margin-top:7px" ${wb.importError ? '' : 'hidden'}>${esc(wb.importError)}</div>
2901
+ <div class="wb-import-actions">
2902
+ <button type="button" class="btn-dark" data-wb-action="do-import">Import</button>
2903
+ <button type="button" class="btn-ghost" data-wb-action="cancel-import">Cancel</button>
2904
+ </div>
2905
+ </div>
2906
+ <div id="wb-steps">${wbStepsHtml()}</div>
2907
+ </div></div>
2908
+ <aside class="wb-aside">
2909
+ <div class="section-label" style="margin:0 0 4px">Skills</div>
2910
+ <div class="wb-hint">Drag into the flow. Order is execution order — the agent applies them top to bottom.</div>
2911
+ <input id="wb-filter" class="filter-input" style="width:100%;margin:0 0 9px" placeholder="Filter skills…" value="${esc(wb.query)}">
2912
+ <div id="wb-palette">${wbPaletteHtml()}</div>
2913
+ <div class="wb-yaml-head">
2914
+ <span class="section-label" style="margin:0">workflow.yaml</span>
2915
+ <span class="spacer"></span>
2916
+ <button type="button" class="btn-text" id="wb-copy" data-wb-action="copy">${wb.copied ? '✓ Copied' : 'Copy'}</button>
2917
+ </div>
2918
+ <pre class="wb-yaml" id="wb-yaml"></pre>
2919
+ <div class="wb-note">
2920
+ <svg viewBox="0 0 24 24" width="12" height="12"><circle cx="12" cy="12" r="9"/><path d="M12 8v.5M12 11v5"/></svg>
2921
+ <span>Portable — export this file and import it in any repo running cezar.</span>
2922
+ </div>
2923
+ </aside>
2924
+ </div>`;
2925
+ $('#wb-yaml').textContent = wbYamlText();
2926
+ }
2927
+
2928
+ /* Structural change (add/move/remove/save): refresh the pieces that depend on
2929
+ the step list without touching the inputs — they keep focus. */
2930
+ function wbRefresh() {
2931
+ $('#wb-steps').innerHTML = wbStepsHtml();
2932
+ $('#wb-palette').innerHTML = wbPaletteHtml();
2933
+ $('#wb-count').textContent = wbCountLabel();
2934
+ $('#wb-load').innerHTML = wbLoadChipsHtml();
2935
+ $('#wb-yaml').textContent = wbYamlText();
2936
+ }
2937
+
2938
+ function wbSkillStep(skill, steps) {
2939
+ const used = new Set(steps.map((s) => s.id));
2940
+ let id = skill;
2941
+ for (let n = 2; used.has(id); n++) id = `${skill}-${n}`;
2942
+ return { id, name: skill, skill, prompt: '{{task}}' };
2943
+ }
2944
+
2945
+ function bindWorkflowsView() {
2946
+ const view = $('#view-workflows');
2947
+
2948
+ view.addEventListener('click', (e) => {
2949
+ if (!state.wb) return;
2950
+ const rm = e.target.closest('[data-wb-remove]');
2951
+ if (rm) {
2952
+ state.wb.steps.splice(Number(rm.dataset.wbRemove), 1);
2953
+ wbRefresh();
2954
+ return;
2955
+ }
2956
+ const load = e.target.closest('[data-wb-load]');
2957
+ if (load) {
2958
+ const name = load.dataset.wbLoad;
2959
+ const w = state.workflows.find((x) => x.name === name);
2960
+ state.wb = name === '__new' ? wbEmpty() : w ? wbFrom(w) : state.wb;
2961
+ renderWorkflowsView();
2962
+ return;
2963
+ }
2964
+ const btn = e.target.closest('[data-wb-action]');
2965
+ if (!btn) return;
2966
+ const action = btn.dataset.wbAction;
2967
+ if (action === 'import') {
2968
+ state.wb.importOpen = !state.wb.importOpen;
2969
+ state.wb.importError = '';
2970
+ renderWorkflowsView();
2971
+ if (state.wb.importOpen) $('#wb-import-text')?.focus();
2972
+ } else if (action === 'cancel-import') {
2973
+ state.wb.importOpen = false;
2974
+ state.wb.importText = '';
2975
+ state.wb.importError = '';
2976
+ renderWorkflowsView();
2977
+ } else if (action === 'do-import') void wbImport(btn);
2978
+ else if (action === 'export') wbExport();
2979
+ else if (action === 'copy') wbCopy();
2980
+ else if (action === 'save') void wbSave(btn);
2981
+ else if (action === 'delete') void wbDelete(btn);
2982
+ });
2983
+
2984
+ view.addEventListener('input', (e) => {
2985
+ if (!state.wb) return;
2986
+ if (e.target.id === 'wb-name') {
2987
+ state.wb.name = e.target.value;
2988
+ $('#wb-yaml').textContent = wbYamlText();
2989
+ $('#wb-load').innerHTML = wbLoadChipsHtml();
2990
+ } else if (e.target.id === 'wb-filter') {
2991
+ state.wb.query = e.target.value;
2992
+ $('#wb-palette').innerHTML = wbPaletteHtml();
2993
+ } else if (e.target.id === 'wb-import-text') {
2994
+ state.wb.importText = e.target.value;
2995
+ }
2996
+ });
2997
+
2998
+ // Drag & drop — palette pills copy in, step cards move; gaps between cards
2999
+ // are the drop targets. Class flips only (no re-render mid-drag: replacing
3000
+ // the dragged node cancels an HTML5 drag).
3001
+ view.addEventListener('dragstart', (e) => {
3002
+ const skill = e.target.closest('.wb-skill');
3003
+ const step = e.target.closest('.wb-step');
3004
+ if (!skill && !step) return;
3005
+ try {
3006
+ e.dataTransfer.setData('text/plain', 'x'); // Firefox needs data to drag
3007
+ e.dataTransfer.effectAllowed = skill ? 'copyMove' : 'move';
3008
+ } catch {
3009
+ // older engines — the drag still works
3010
+ }
3011
+ state.wbDrag = skill
3012
+ ? { from: 'palette', skill: skill.dataset.skill }
3013
+ : { from: 'step', index: Number(step.dataset.idx) };
3014
+ // Deferred: repainting the dragged node in the same tick aborts the drag.
3015
+ setTimeout(() => {
3016
+ view.classList.add('wb-dragging');
3017
+ step?.classList.add('drag-src');
3018
+ }, 0);
3019
+ });
3020
+ view.addEventListener('dragover', (e) => {
3021
+ const gap = e.target.closest('.wb-gap');
3022
+ if (!gap || !state.wbDrag) return;
3023
+ e.preventDefault();
3024
+ e.dataTransfer.dropEffect = state.wbDrag.from === 'palette' ? 'copy' : 'move';
3025
+ gap.classList.add('over');
3026
+ });
3027
+ view.addEventListener('dragleave', (e) => {
3028
+ e.target.closest('.wb-gap')?.classList.remove('over');
3029
+ });
3030
+ view.addEventListener('drop', (e) => {
3031
+ const gap = e.target.closest('.wb-gap');
3032
+ const d = state.wbDrag;
3033
+ state.wbDrag = null;
3034
+ view.classList.remove('wb-dragging');
3035
+ if (!gap || !d) return;
3036
+ e.preventDefault();
3037
+ const at = Number(gap.dataset.gap);
3038
+ const steps = state.wb.steps;
3039
+ if (d.from === 'step') {
3040
+ const [moved] = steps.splice(d.index, 1);
3041
+ steps.splice(d.index < at ? at - 1 : at, 0, moved);
3042
+ } else {
3043
+ if (steps.length >= WB_MAX_STEPS) {
3044
+ alertBar(`A workflow holds at most ${WB_MAX_STEPS} steps.`);
3045
+ wbRefresh();
3046
+ return;
3047
+ }
3048
+ steps.splice(at, 0, wbSkillStep(d.skill, steps));
3049
+ }
3050
+ wbRefresh();
3051
+ });
3052
+ view.addEventListener('dragend', () => {
3053
+ state.wbDrag = null;
3054
+ view.classList.remove('wb-dragging');
3055
+ for (const el of view.querySelectorAll('.over, .drag-src')) el.classList.remove('over', 'drag-src');
3056
+ });
3057
+ }
3058
+
3059
+ async function wbImport(btn) {
3060
+ const text = state.wb.importText.trim();
3061
+ if (!text) {
3062
+ $('#wb-import-text')?.focus();
3063
+ return;
3064
+ }
3065
+ btn.disabled = true;
3066
+ try {
3067
+ const res = await fetch('/api/workflows/parse', {
3068
+ method: 'POST',
3069
+ headers: { 'content-type': 'application/json' },
3070
+ body: JSON.stringify({ yaml: text }),
3071
+ });
3072
+ const data = await res.json();
3073
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
3074
+ state.wb = { ...wbEmpty(), name: data.name, description: data.description ?? '', steps: data.steps };
3075
+ renderWorkflowsView();
3076
+ alertBar(`Imported "${data.name}" — review, then Save.`);
624
3077
  } catch (err) {
625
- view.innerHTML = `<div class="panel">✗ ${esc(err.message)}</div>`;
3078
+ state.wb.importError = err.message;
3079
+ renderWorkflowsView();
3080
+ } finally {
3081
+ btn.disabled = false;
626
3082
  }
627
3083
  }
628
3084
 
3085
+ function wbSlug() {
3086
+ return (
3087
+ state.wb.name
3088
+ .trim()
3089
+ .toLowerCase()
3090
+ .replace(/[^a-z0-9]+/g, '-')
3091
+ .replace(/^-+|-+$/g, '') || 'workflow'
3092
+ );
3093
+ }
3094
+
3095
+ function wbExport() {
3096
+ const blob = new Blob([wbYamlText()], { type: 'text/yaml' });
3097
+ const url = URL.createObjectURL(blob);
3098
+ const a = document.createElement('a');
3099
+ a.href = url;
3100
+ a.download = `${wbSlug()}.yaml`;
3101
+ document.body.appendChild(a);
3102
+ a.click();
3103
+ a.remove();
3104
+ setTimeout(() => URL.revokeObjectURL(url), 1000);
3105
+ }
3106
+
3107
+ let wbCopyTimer = null;
3108
+ function wbCopy() {
3109
+ void navigator.clipboard?.writeText(wbYamlText()).catch(() => {});
3110
+ state.wb.copied = true;
3111
+ const btn = $('#wb-copy');
3112
+ if (btn) btn.textContent = '✓ Copied';
3113
+ clearTimeout(wbCopyTimer);
3114
+ wbCopyTimer = setTimeout(() => {
3115
+ if (state.wb) state.wb.copied = false;
3116
+ const b = $('#wb-copy');
3117
+ if (b) b.textContent = 'Copy';
3118
+ }, 1600);
3119
+ }
3120
+
3121
+ async function wbSave(btn) {
3122
+ const wb = state.wb;
3123
+ const name = wb.name.trim();
3124
+ if (!name) {
3125
+ $('#wb-name')?.focus();
3126
+ return;
3127
+ }
3128
+ if (!wb.steps.length) {
3129
+ alertBar('Add at least one step first.');
3130
+ return;
3131
+ }
3132
+ const stack = wbSkillStack(wb.steps);
3133
+ const body = {
3134
+ name,
3135
+ ...(wb.description.trim() ? { description: wb.description.trim() } : {}),
3136
+ ...(stack ? { skills: stack } : { steps: wb.steps }),
3137
+ };
3138
+ const post = (payload) =>
3139
+ fetch('/api/workflows', {
3140
+ method: 'POST',
3141
+ headers: { 'content-type': 'application/json' },
3142
+ body: JSON.stringify(payload),
3143
+ });
3144
+ btn.disabled = true;
3145
+ try {
3146
+ let res = await post(body);
3147
+ let data = await res.json();
3148
+ if (res.status === 409 && data.exists) {
3149
+ if (!confirm(`"${name}" already exists — overwrite it?`)) return;
3150
+ res = await post({ ...body, overwrite: true });
3151
+ data = await res.json();
3152
+ }
3153
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
3154
+ alertBar(`Saved — ${String(data.path).split('/').pop()}`);
3155
+ const workflowsRes = await getJson('/api/workflows');
3156
+ setWorkflowOptions(workflowsRes.workflows);
3157
+ renderWorkflowsView(); // chips + the Delete button now reflect the file
3158
+ } catch (err) {
3159
+ alertBar(err.message);
3160
+ } finally {
3161
+ btn.disabled = false;
3162
+ }
3163
+ }
3164
+
3165
+ async function wbDelete(btn) {
3166
+ const name = state.wb.name.trim();
3167
+ const fileWf = state.workflows.find((w) => w.name === name && w.source === 'file');
3168
+ if (!fileWf) return;
3169
+ if (!confirm(`Delete workflow "${name}" (${String(fileWf.path ?? '').split('/').pop()})?`)) return;
3170
+ btn.disabled = true;
3171
+ try {
3172
+ const res = await fetch(`/api/workflows/${encodeURIComponent(name)}`, { method: 'DELETE' });
3173
+ const data = await res.json().catch(() => ({}));
3174
+ if (!res.ok) throw new Error(data.error ?? `HTTP ${res.status}`);
3175
+ alertBar(`Deleted "${name}".`);
3176
+ const workflowsRes = await getJson('/api/workflows');
3177
+ setWorkflowOptions(workflowsRes.workflows);
3178
+ state.wb = wbEmpty();
3179
+ renderWorkflowsView();
3180
+ } catch (err) {
3181
+ alertBar(err.message);
3182
+ btn.disabled = false;
3183
+ }
3184
+ }
3185
+
3186
+ // ---- bookmarklet generator (spec 011) ------------------------------------------
3187
+
3188
+ /* The javascript: URL dragged to the bookmarks bar. On a GitHub PR/issue it
3189
+ scans localhost:4321–4330 for cockpits (GET /api/health, 800 ms timeout,
3190
+ CORS-enabled server-side), picks the one whose repo.remote matches the
3191
+ page's owner/repo (fallback: first alive) and opens /new there. The whole
3192
+ program is one URI-encoded expression — no external state. */
3193
+ function bookmarkletUrl(skillName, auto, key) {
3194
+ const enc = (s) => encodeURIComponent(s).replaceAll("'", '%27'); // ' survives encodeURIComponent — would break the JS string
3195
+ const query = `${skillName ? `skill=${enc(skillName)}&` : ''}auto=${auto ? '1' : '0'}&key=${enc(key)}&ref=`;
3196
+ const code =
3197
+ `(async()=>{const m=location.href.match(/^https:\\/\\/github\\.com\\/([^\\/]+)\\/([^\\/]+)\\/(pull|issues)\\/\\d+/);` +
3198
+ `if(!m){alert('Open a GitHub PR or issue first');return;}` +
3199
+ `const q='${query}'+encodeURIComponent(location.href);` +
3200
+ `const f=async p=>{try{const c=new AbortController();setTimeout(()=>c.abort(),800);` +
3201
+ `const r=await fetch('http://localhost:'+p+'/api/health',{signal:c.signal});const h=await r.json();` +
3202
+ `return{p,remote:(h.repo&&h.repo.remote)||''}}catch(e){return null}};` +
3203
+ `const rs=(await Promise.all([4321,4322,4323,4324,4325,4326,4327,4328,4329,4330].map(f))).filter(Boolean);` +
3204
+ `if(!rs.length){alert('cezar cockpit is not running - start it with: npx cezar');return;}` +
3205
+ `const t=rs.find(r=>r.remote.includes(m[1]+'/'+m[2]))||rs[0];` +
3206
+ `open('http://localhost:'+t.p+'/new?'+q,'_blank');})();`;
3207
+ return `javascript:${encodeURIComponent(code)}`;
3208
+ }
3209
+
3210
+ function bookmarkletShellHtml() {
3211
+ return `
3212
+ <div class="inner" id="bm-panel">
3213
+ <h1>Run from GitHub</h1>
3214
+ <div class="bm-help">Drag a button below to your browser's bookmarks bar.
3215
+ On any GitHub PR or issue, click it — it finds your running cockpit on
3216
+ localhost (ports 4321–4330) and picks the one serving that repo.
3217
+ The cockpit must be running: <span class="mono">npx cezar</span>.</div>
3218
+ <label class="bm-auto"><input type="checkbox" id="bm-auto">
3219
+ One-click launch (auto-submit) <span class="dim">— re-drag the buttons after changing this</span></label>
3220
+ <div id="bm-generic"></div>
3221
+ <input id="bm-filter" class="bm-filter" placeholder="Filter skills…">
3222
+ <div id="bm-list"></div>
3223
+ </div>`;
3224
+ }
3225
+
3226
+ function bmRowHtml(label, url, hint) {
3227
+ return `
3228
+ <div class="bm-row">
3229
+ <a class="bm" draggable="true" href="${esc(url)}" title="Drag me to your bookmarks bar">⚡ ${esc(label)}</a>
3230
+ <button type="button" class="bm-copy" data-copy="${esc(url)}" title="Copy the bookmarklet URL">Copy</button>
3231
+ ${hint ? `<span class="dim bm-hint">${esc(hint)}</span>` : ''}
3232
+ </div>`;
3233
+ }
3234
+
3235
+ function renderBmLinks(skills) {
3236
+ const key = state.launchKey ?? '';
3237
+ // Generic launcher: no skill, auto forced off — it only prefills the form.
3238
+ $('#bm-generic').innerHTML = bmRowHtml(
3239
+ 'cezar: this PR/issue',
3240
+ bookmarkletUrl('', false, key),
3241
+ 'prefills the form — nothing starts by itself',
3242
+ );
3243
+ const filter = state.bmFilter.trim().toLowerCase();
3244
+ const filtered = skills.filter((s) => s.name.toLowerCase().includes(filter));
3245
+ $('#bm-list').innerHTML = filtered.length
3246
+ ? filtered
3247
+ .map((s) => bmRowHtml(`/${s.name}`, bookmarkletUrl(s.name, state.bmAuto, key), s.source))
3248
+ .join('')
3249
+ : `<div class="dim">${skills.length ? '(no skills match)' : '(no skills yet — the generic launcher above still works)'}</div>`;
3250
+ }
3251
+
3252
+ async function bindBookmarklets(skills) {
3253
+ if (state.launchKey === null) {
3254
+ try {
3255
+ state.launchKey = (await getJson('/api/launch-key')).key;
3256
+ } catch {
3257
+ state.launchKey = ''; // degraded: bookmarklets still work, auto-start won't
3258
+ }
3259
+ }
3260
+ const panel = $('#bm-panel');
3261
+ if (!panel) return; // skills view re-rendered meanwhile
3262
+ const autoBox = $('#bm-auto');
3263
+ autoBox.checked = state.bmAuto;
3264
+ autoBox.addEventListener('change', () => {
3265
+ state.bmAuto = autoBox.checked;
3266
+ renderBmLinks(skills);
3267
+ });
3268
+ const filterBox = $('#bm-filter');
3269
+ filterBox.value = state.bmFilter;
3270
+ filterBox.addEventListener('input', () => {
3271
+ state.bmFilter = filterBox.value;
3272
+ renderBmLinks(skills);
3273
+ });
3274
+ panel.addEventListener('click', async (e) => {
3275
+ const link = e.target.closest('a.bm');
3276
+ if (link) {
3277
+ // The cockpit page never executes the javascript: URL itself — the
3278
+ // links are only a drag source (spec 011 §5).
3279
+ e.preventDefault();
3280
+ alertBar('Drag me to your bookmarks bar');
3281
+ return;
3282
+ }
3283
+ const copy = e.target.closest('button[data-copy]');
3284
+ if (copy) {
3285
+ try {
3286
+ await navigator.clipboard.writeText(copy.dataset.copy);
3287
+ alertBar('Bookmarklet URL copied.');
3288
+ } catch {
3289
+ alertBar('Copy failed — drag the button instead.');
3290
+ }
3291
+ }
3292
+ });
3293
+ renderBmLinks(skills);
3294
+ }
3295
+
629
3296
  init().catch((err) => {
630
3297
  document.body.insertAdjacentHTML(
631
3298
  'beforeend',