/** * Browser module for the factory app. Plain DOM, no framework, no inline * handlers. Reads only via GET; writes only on explicit user submits. * Written without backticks or template placeholders so it can live in String.raw. */ export const CLIENT_JS = String.raw` const $ = (s, r) => (r || document).querySelector(s); const $$ = (s, r) => Array.from((r || document).querySelectorAll(s)); const BP = document.body.dataset.base || ''; const VIEW = document.body.dataset.view; const ICONS = JSON.parse($('#icons').textContent || '{}'); const TZ = 'America/Denver'; const TERMINAL = ['shipped', 'dropped']; const STATES = { intake: ['New', 'Just arrived. Waiting for triage.'], triaged: ['Triaged', 'Reviewed and accepted. Waiting to be planned.'], planned: ['Ready to start', 'Planned. Waiting for an agent session to start.'], running: ['Building', 'An agent session is working on this.'], verifying: ['Verifying', 'The work is done and being checked.'], 'needs-kent': ['Needs you', 'Waiting on your decision before it can move.'], shipped: ['Shipped', 'Completed and shipped.'], dropped: ['Stopped', 'Closed without shipping.'] }; const SOURCES = { manual: ['Manual', 'pencil', '#4f46e5', '#eef0ff'], friction: ['Friction', 'zap', '#b45309', '#fff4e0'], feedback: ['Feedback', 'message', '#0f766e', '#e8f6f3'], 'github-issues': ['GitHub issue', 'branch', '#334155', '#eef1f5'], 'ci-failure': ['CI failure', 'alert', '#b42318', '#fdeeec'], 'ci-review': ['CI review', 'pulse', '#0f766e', '#e8f6f3'], sentry: ['Sentry', 'alert', '#6d28d9', '#f3eeff'], discord: ['Discord', 'message', '#4338ca', '#eef0ff'], email: ['Email', 'mail', '#0369a1', '#e8f4fb'], x: ['X', 'message', '#334155', ''] }; const PALETTE = ['#4f46e5', '#0f766e', '#b45309', '#be185d', '#0369a1', '#6d28d9', '#15803d']; const PRIO_COLORS = ['#dc2626', '#f59e0b', '#6366f1', '#94a3b8']; function icon(name) { const s = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); s.setAttribute('class', 'icon'); s.setAttribute('viewBox', '0 0 24 24'); s.setAttribute('aria-hidden', 'true'); s.innerHTML = ICONS[name] || ''; return s; } function h(tag, attrs) { const el = document.createElement(tag); const a = attrs || {}; for (const k of Object.keys(a)) { const v = a[k]; if (v == null || v === false) continue; if (k === 'class') el.className = v; else if (k === 'text') el.textContent = v; else if (k.slice(0, 2) === 'on') el.addEventListener(k.slice(2), v); else el.setAttribute(k, v === true ? '' : String(v)); } const kids = Array.prototype.slice.call(arguments, 2).flat(3); for (const c of kids) { if (c == null || c === false) continue; el.append(c.nodeType ? c : document.createTextNode(String(c))); } return el; } function fill(el, nodes) { if (el) el.replaceChildren.apply(el, [].concat(nodes).filter((n) => n != null && n !== false)); } const url = (p) => BP + p; async function getJson(path) { const r = await fetch(url(path), { headers: { accept: 'application/json' } }); if (!r.ok) throw new Error('Request failed (' + r.status + ')'); return r.json(); } function errorBox(msg) { return h('div', { class: 'notice', role: 'alert' }, icon('alert'), h('div', null, h('strong', { text: "Couldn't load this view." }), h('p', null, msg + ' ', h('a', { href: location.href, text: 'Try again' })))); } function plural(n, one, many) { return n + ' ' + (n === 1 ? one : (many || one + 's')); } function yearOf(d) { return new Intl.DateTimeFormat('en-US', { timeZone: TZ, year: 'numeric' }).format(d); } function fmtDate(iso) { const d = new Date(iso); if (isNaN(d.getTime())) return ''; const o = { timeZone: TZ, month: 'short', day: 'numeric' }; if (yearOf(d) !== yearOf(new Date())) o.year = 'numeric'; return new Intl.DateTimeFormat('en-US', o).format(d); } function fmtFull(iso) { const d = new Date(iso); if (isNaN(d.getTime())) return ''; return new Intl.DateTimeFormat('en-US', { timeZone: TZ, dateStyle: 'medium', timeStyle: 'short' }).format(d) + ' MT'; } function age(iso) { const s = (Date.now() - Date.parse(iso)) / 1000; if (!isFinite(s)) return ''; if (s < 60) return 'just now'; if (s < 3600) return Math.floor(s / 60) + 'm ago'; if (s < 86400) return Math.floor(s / 3600) + 'h ago'; if (s < 7 * 86400) return Math.floor(s / 86400) + 'd ago'; return fmtDate(iso); } function hash(s) { let x = 0; for (const c of s) x = (x * 31 + c.charCodeAt(0)) >>> 0; return x; } function initials(name) { const words = String(name).trim().split(/[\s_-]+/).filter(Boolean); if (words.length > 1) return (words[0][0] + words[1][0]).toUpperCase(); const w = words[0] || '?'; const cap = w.slice(1).match(/[A-Z]/); return (w[0] + (cap ? cap[0] : '')).toUpperCase(); } function mono(p, small) { const c = PALETTE[hash(p.id) % PALETTE.length]; return h('span', { class: 'mono tint' + (small ? ' sm' : ''), style: '--c:' + c, 'aria-hidden': 'true', text: initials(p.displayName || p.id) }); } function runnerLabel(id) { return id === 'devin' ? 'Devin' : id === 'single-agent' ? 'Single agent' : id; } function runner(id) { return h('span', { class: 'runner' }, h('span', { class: 'mono sm runner-mono', 'aria-hidden': 'true', text: runnerLabel(id)[0] }), runnerLabel(id)); } function repoOf(r) { const text = r.repoRef; if (r.host && r.host !== 'github') return h('span', { class: 'repo', text: text }); return h('a', { class: 'repo', href: 'https://github.com/' + text, rel: 'noreferrer', target: '_blank' }, text, h('span', { class: 'sr', text: ' (opens GitHub)' })); } function stateChip(state) { const s = STATES[state] || [state, '']; return h('span', { class: 'chip st-' + state, title: s[1], text: s[0] }); } function sourceOf(item) { let key = item.source; if (key === 'manual') for (const l of item.labels || []) if (l === 'friction' || l === 'feedback') key = l; return SOURCES[key] || [item.source, 'inbox', '#475569', '#eef1f5']; } function sessionUrl(item) { // The server fills sessionUrl from the item's runner (start URL or sessionUrlTemplate). return item && typeof item.sessionUrl === 'string' && /^https:\/\//.test(item.sessionUrl) ? item.sessionUrl : null; } let PROJECTS = []; const projectName = (id) => { const p = PROJECTS.find((x) => x.id === id); return p ? p.displayName : id; }; function toast(msg) { const t = $('#toast'); t.textContent = msg; t.hidden = false; clearTimeout(toast.timer); toast.timer = setTimeout(() => { t.hidden = true; }, 6000); } function row(item) { const src = sourceOf(item); const meta = [h('span', { text: projectName(item.projectId) })]; if (item.repoRef) meta.push(h('span', { class: 'repo', text: item.repoRef })); if (item.priority != null) meta.push(h('span', { class: 'prio', title: 'Priority ' + item.priority, text: 'P' + item.priority })); meta.push(h('span', { title: fmtFull(item.createdAt), text: 'Added ' + age(item.createdAt) })); return h('button', { type: 'button', class: 'row', 'data-id': item.id, onclick: () => openItem(item) }, h('span', { class: 'src tint', style: '--c:' + src[2], title: src[0] }, icon(src[1]), h('span', { class: 'sr', text: src[0] })), h('span', null, h('span', { class: 'row-title', text: item.title }), h('span', { class: 'row-meta' }, meta)), stateChip(item.state)); } // A card outside the current list (finished, filtered, or older): load it directly. async function openCardById(id) { try { const r = await fetch(url('/api/cards/' + encodeURIComponent(id)), { headers: { accept: 'application/json' } }); if (!r.ok) return; const d = await r.json(); if (d && d.item) openItem(d.item); } catch (e) { /* the list still shows; nothing else to do */ } } const REPORT_LABELS = { shipped: 'Shipped', done: 'Done', parked: 'Parked', progress: 'Progress', blocked: 'Blocked', failed: 'Failed' }; function safeHref(u) { try { const x = new URL(u); return x.protocol === 'https:' ? x.toString() : null; } catch (e) { return null; } } function reportList(item) { const reports = (item.events || []).filter((e) => e.meta && e.meta.report).slice(-5).reverse(); if (!reports.length) return null; return h('section', { class: 'stack' }, h('h3', { text: 'Agent reports' }), h('ul', { class: 'events' }, reports.map((e) => { const r = e.meta.report; const who = r.agent ? (r.agent.name || r.agent.kind) : e.actor; const links = []; const pr = r.prUrl && safeHref(r.prUrl); if (pr) links.push(h('a', { href: pr, target: '_blank', rel: 'noreferrer', text: 'Pull request' })); const ag = r.agent && r.agent.url && safeHref(r.agent.url); if (ag) links.push(h('a', { href: ag, target: '_blank', rel: 'noreferrer', text: 'Agent session' })); (r.links || []).forEach((l) => { const href = safeHref(l.url); if (href) links.push(h('a', { href: href, target: '_blank', rel: 'noreferrer', text: l.label || new URL(href).hostname })); }); return h('li', null, h('div', null, h('strong', { text: (REPORT_LABELS[r.outcome] || r.outcome) + (r.title ? ': ' + r.title : '') })), h('div', { class: 'body-text', text: r.summary }), links.length ? h('div', { class: 'small' }, links.reduce((acc, a, i) => (i ? acc.concat([' · ', a]) : [a]), [])) : null, h('div', { class: 'muted small', text: fmtFull(e.at) + ' · ' + who })); }))); } function openItem(item) { const dlg = $('#item-dialog'); const st = STATES[item.state] || [item.state, '']; const project = PROJECTS.find((p) => p.id === item.projectId); const sess = sessionUrl(item); const dl = h('dl', { class: 'meta' }); const add = (k, v) => { if (v != null && v !== '') dl.append(h('dt', { text: k }), h('dd', null, v)); }; add('Project', project ? project.displayName : item.projectId); add('Repository', item.repoRef ? repoOf({ repoRef: item.repoRef, host: 'github' }) : null); add('Source', sourceOf(item)[0]); add('Priority', item.priority != null ? 'P' + item.priority : 'Not set'); add('Added', fmtFull(item.createdAt)); add('Updated', fmtFull(item.updatedAt)); if (item.shadow) add('Intake', 'Added while shadow mode was on'); if (item.labels && item.labels.length) add('Labels', item.labels.join(', ')); add('ID', h('code', { text: item.id })); // Short card link for PR bodies: "Closes " ships the card when the PR merges. const linkBase = ((DATA && DATA.settings && DATA.settings.publicBaseUrl) || (location.origin + BP)).replace(/\/+$/, ''); add('Card link', h('code', { text: linkBase + '/c/' + item.id })); const events = (item.events || []).slice(-5).reverse().map((e) => h('li', null, h('div', null, h('strong', { text: (e.from ? (STATES[e.from] || [e.from])[0] + ' → ' : '') + (STATES[e.to] || [e.to])[0] })), h('div', { class: 'muted' }, String(e.reason || '').replace(/^./, (c) => c.toUpperCase())), h('div', { class: 'muted small', text: fmtFull(e.at) + ' · ' + e.actor }))); const tl = colTimeline(item.events, item.state, item.createdAt, 0, BOARD_COL_LABELS); fill($('#item-body'), [ h('div', { class: 'dlg-head' }, h('div', null, stateChip(item.state), h('h2', { id: 'item-title', style: 'margin-top:10px', text: item.title })), h('button', { type: 'button', class: 'icon-btn', 'aria-label': 'Close', onclick: () => dlg.close() }, icon('close'))), h('p', { class: 'muted', text: st[1] }), item.why ? h('p', { class: 'small' }, h('strong', { text: 'Why it ranks here: ' }), item.why.split('; ').join(' · ')) : null, item.body ? h('div', { class: 'body-text', text: item.body }) : null, dl, sess ? h('div', null, h('a', { class: 'btn', href: sess, target: '_blank', rel: 'noreferrer' }, icon('external'), 'Open Devin session')) : null, item.reportRef && /^rp_[a-z0-9]{16}$/.test(item.reportRef.id) ? h('div', null, h('a', { class: 'btn', href: url('/reports/' + item.reportRef.id) }, icon('report'), 'Open the report this came from')) : null, reportList(item), tl ? h('section', { class: 'stack' }, h('h3', { text: 'Column history' }), tl) : null, events.length ? h('section', { class: 'stack' }, h('h3', { text: 'Recent activity' }), h('ul', { class: 'events' }, events)) : null ]); dlg.showModal(); } // One composite GET per page load (/api/bootstrap), shared by every view and the // create dialog. Cached per tab in sessionStorage: under FRESH_MS it paints with // no request; older data paints at once and refreshes in the background. // Every write path calls invalidateData() so the next view refetches. // One composite GET (/api/bootstrap) shared by every view and the create dialog. // The last good snapshot (minus settings) is kept in localStorage so the app // opens offline with a "last synced" label. Under FRESH_MS it paints with no // request; older data paints at once and refreshes in the background. const DATA_KEY = 'factory:snapshot:v1'; const FRESH_MS = 15000; let DATA = null, DATA_AT = 0, DATA_P = null, RENDER = null; function readCachedData() { if (DATA) return; try { const c = JSON.parse(localStorage.getItem(DATA_KEY) || 'null'); if (c && c.at && c.data && c.data.snapshot) { DATA = c.data; DATA_AT = c.at; } } catch (e) {} } function invalidateData() { DATA_AT = 0; } function clearCachedData() { DATA = null; DATA_AT = 0; try { localStorage.removeItem(DATA_KEY); localStorage.removeItem(DRAFT_KEY); sessionStorage.removeItem('factory:bootstrap:v1'); } catch (e) {} } function fetchData() { if (!DATA_P) { DATA_P = getJson('/api/bootstrap').then((d) => { DATA = d; DATA_AT = Date.now(); const safe = Object.assign({}, d, { settings: null }); try { localStorage.setItem(DATA_KEY, JSON.stringify({ at: DATA_AT, data: safe })); } catch (e) {} setNet(); return d; }).finally(() => { DATA_P = null; }); } return DATA_P; } async function withData(paint) { readCachedData(); if (DATA) { PROJECTS = DATA.snapshot.projects; paint(DATA); if (Date.now() - DATA_AT < FRESH_MS) return; const before = JSON.stringify(DATA); try { const d = await fetchData(); if (JSON.stringify(d) !== before) { PROJECTS = d.snapshot.projects; paint(d); } } catch (e) { setNet(); } return; } const d = await fetchData(); PROJECTS = d.snapshot.projects; paint(d); } // Small fixed status pill: offline/stale/draft/update. Fixed position, so it never shifts layout. const NET = { update: null }; const INSTALL = { prompt: null }; window.addEventListener('beforeinstallprompt', (e) => { e.preventDefault(); INSTALL.prompt = e; const b = $('#install-app'); if (b) b.hidden = false; }); function setNet() { const el = $('#net'); if (!el) return; const text = $('#net-text'), btn = $('#net-action'); const draft = readDraft(); const offline = navigator.onLine === false; let state = '', msg = ''; if (NET.update) { state = 'update'; msg = 'Update available'; } else if (offline) { state = 'offline'; msg = 'Offline' + (DATA_AT ? ' · data from ' + fmtFull(new Date(DATA_AT).toISOString()) : ''); } if (draft && draft.pending) { state = state || 'draft'; msg = (msg ? msg + ' · ' : '') + 'Draft waiting to sync'; } el.dataset.state = state; text.textContent = msg; btn.hidden = state !== 'update'; btn.textContent = 'Refresh'; $$('[data-online-only], form[method=post] [type=submit]').forEach((b) => { b.disabled = offline; if (offline) b.title = 'Reconnect to use this'; else if (b.title === 'Reconnect to use this') b.removeAttribute('title'); }); } // Add-work drafts: saved as you type; an offline submit waits and is sent once // on reconnect with the same idempotency key, so a retry never adds twice. const DRAFT_KEY = 'factory:create-draft:v1'; function readDraft() { try { return JSON.parse(localStorage.getItem(DRAFT_KEY) || 'null'); } catch (e) { return null; } } function writeDraft(d) { try { if (d) localStorage.setItem(DRAFT_KEY, JSON.stringify(d)); else localStorage.removeItem(DRAFT_KEY); } catch (e) {} } function newKey() { return (crypto.randomUUID ? crypto.randomUUID() : String(Date.now()) + Math.random().toString(16).slice(2)).replace(/[^A-Za-z0-9]/g, '').slice(0, 32); } async function postCreate(body) { const r = await fetch(url('/api/create'), { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(body) }); const data = await r.json().catch(() => ({})); if (!r.ok || !data.ok) { const e = new Error(data.error || 'Something went wrong (' + r.status + ').'); e.status = r.status; throw e; } return data; } let FLUSHING = false; async function flushDraft() { const d = readDraft(); if (!d || !d.pending || FLUSHING || navigator.onLine === false) return; FLUSHING = true; try { const data = await postCreate(d.body); writeDraft(null); invalidateData(); toast('Synced your draft: “' + data.item.title + '” is in the queue as New.'); if (RENDER) RENDER(); } catch (e) { if (e.status) { writeDraft(Object.assign({}, d, { pending: false, error: e.message })); toast('Your draft needs attention: ' + e.message); } } finally { FLUSHING = false; setNet(); } } window.addEventListener('online', () => { setNet(); invalidateData(); flushDraft(); if (RENDER) RENDER(); }); window.addEventListener('offline', () => setNet()); const cmpItems = (a, b) => (a.rank - b.rank) || ((Date.parse(a.createdAt) || 0) - (Date.parse(b.createdAt) || 0)) || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0); // Rebuilds /api/queue?includeTerminal=1 (first 100 of every item) from open + finished. function allWork(d) { return { items: d.queue.items.concat(d.finished.items).sort(cmpItems).slice(0, 100), total: d.queue.total + d.finished.total }; } async function loadProjects() { if (!PROJECTS.length) { readCachedData(); PROJECTS = (DATA || await fetchData()).snapshot.projects; } return PROJECTS; } function setupCreate() { const dlg = $('#create-dialog'); const form = $('#create-form'); const projSel = $('#cf-project'); const repoSel = $('#cf-repo'); const err = $('#create-error'); const submit = form.querySelector('[type=submit]'); const fillRepos = () => { const p = PROJECTS.find((x) => x.id === projSel.value); const repos = p ? p.repos.filter((r) => r.enabled) : []; fill(repoSel, repos.length ? repos.map((r) => h('option', { value: r.repoRef, text: r.repoRef })) : [h('option', { value: '', text: 'No repository' })]); }; projSel.addEventListener('change', fillRepos); $$('[data-open-create]').forEach((b) => b.addEventListener('click', async () => { err.hidden = true; try { await loadProjects(); } catch (e) { toast('Could not load projects. Try again.'); return; } const enabled = PROJECTS.filter((p) => p.enabled); const preset = new URLSearchParams(location.search).get('project'); fill(projSel, enabled.map((p) => h('option', { value: p.id, selected: p.id === preset, text: p.displayName }))); const draft = readDraft(); if (draft && draft.fields && !draft.pending) { const f = form.elements, v = draft.fields; if (enabled.some((p) => p.id === v.projectId)) projSel.value = v.projectId; fillRepos(); f.title.value = v.title || ''; f.body.value = v.body || ''; f.kind.value = v.kind || 'general'; f.priority.value = v.priority || ''; if (v.repoRef) repoSel.value = v.repoRef; if (draft.error) { err.textContent = draft.error; err.hidden = false; } } else fillRepos(); submit.disabled = !enabled.length || Boolean(draft && draft.pending); if (draft && draft.pending) { err.textContent = 'A draft is already waiting to sync. It will be added when you reconnect.'; err.hidden = false; } if (!enabled.length) { err.textContent = 'Turn on a project in Manage projects before adding work.'; err.hidden = false; } dlg.showModal(); form.elements.title.focus(); })); const fieldsOf = () => { const f = form.elements; return { projectId: f.projectId.value, title: f.title.value, body: f.body.value, kind: f.kind.value, priority: f.priority.value, repoRef: f.repoRef.value }; }; form.addEventListener('input', () => { const d = readDraft(); if (d && d.pending) return; writeDraft({ key: (d && d.key) || newKey(), fields: fieldsOf(), at: Date.now() }); }); form.addEventListener('submit', async (ev) => { ev.preventDefault(); if (submit.disabled) return; const f = form.elements; const title = f.title.value.trim(); if (!title) { err.textContent = 'Add a title so you can recognize this work later.'; err.hidden = false; f.title.focus(); return; } err.hidden = true; const prior = readDraft(); const key = (prior && prior.key) || newKey(); const body = { projectId: f.projectId.value, title: title, body: f.body.value, kind: f.kind.value, priority: f.priority.value === '' ? null : Number(f.priority.value), repoRef: f.repoRef.value || null, idempotencyKey: key }; if (navigator.onLine === false) { writeDraft({ key: key, fields: fieldsOf(), body: body, pending: true, at: Date.now() }); dlg.close(); setNet(); toast('Saved as a draft. It will be added once when you reconnect.'); return; } submit.disabled = true; submit.textContent = 'Adding…'; try { const data = await postCreate(body); writeDraft(null); invalidateData(); sessionStorage.setItem('factory:toast', 'Added “' + data.item.title + '” to the queue as New.'); location.assign(url('/work?created=' + encodeURIComponent(data.item.id))); } catch (e) { if (!e.status) { writeDraft({ key: key, fields: fieldsOf(), body: body, pending: true, at: Date.now() }); dlg.close(); setNet(); toast('Connection lost. Saved as a draft; it will be added once when you reconnect.'); } else { err.textContent = e.message; err.hidden = false; } submit.disabled = false; submit.textContent = 'Add to queue'; } }); } function stat(label, value, hint, href) { return h('a', { class: 'stat', href: url(href) }, h('span', { text: label }), h('b', { text: String(value) }), h('small', { text: hint })); } function projectCard(p, open, needs) { const repos = p.repos || []; return h('article', { class: 'card pcard' }, h('div', { class: 'ptop' }, mono(p), h('div', null, h('h3', { text: p.displayName }), h('code', { class: 'muted', text: p.id }))), h('div', { class: 'stack', style: 'gap:6px' }, repos.length ? repos.map(repoOf) : h('span', { class: 'muted small', text: 'No repository yet' })), open == null ? null : h('p', { class: 'small muted', text: plural(open, 'open item') + (needs ? ' · ' + needs + ' need you' : '') }), h('div', { class: 'pmeta' }, runner(p.defaultRunnerId), h('span', { class: 'chip ' + (p.enabled ? 'on' : 'off'), text: p.enabled ? 'Enabled' : 'Disabled' })), open == null ? null : h('a', { class: 'link', href: url('/projects/' + encodeURIComponent(p.id)) }, 'View project')); } function flowDiagram() { const steps = [['Intake', 'Signals arrive'], ['Prioritize', 'Ranked P0–P3'], ['Build', 'Devin works it'], ['Ship', 'You merge']]; return h('ol', { class: 'flow', 'aria-label': 'How work moves' }, steps.map((s, i) => h('li', null, h('i', { text: String(i + 1) }), h('b', { text: s[0] }), s[1]))); } async function renderOverview() { try { await withData(paintOverview); } catch (e) { fill($('#overview-queue'), errorBox(e.message)); fill($('#stats'), []); } } function paintOverview(d) { { const s = d.snapshot, q = d.queue; const by = s.counts.byState || {}; const enabled = PROJECTS.filter((p) => p.enabled).length; $('#shadow-badge').hidden = !s.policy.shadowMode; $('#shadow-note').hidden = !s.policy.shadowMode; const needs = by['needs-kent'] || 0; const prog = (by.running || 0) + (by.verifying || 0); fill($('#stats'), [ stat('Active projects', enabled, plural(PROJECTS.length, 'project') + ' configured', '/projects'), stat('Needs your attention', needs, needs ? 'Waiting on a decision' : 'Nothing waiting on you', '/work?status=needs'), stat('In progress', prog, 'Building or verifying', '/work?status=active'), stat('Open work', q.total, 'Everything not yet finished', '/work') ]); const status = h('div', { class: 'statusline' }, h('span', { class: 'dot' + (enabled ? '' : ' off') }), enabled === PROJECTS.length ? 'Your ' + plural(enabled, 'project') + (enabled === 1 ? ' is' : ' are') + ' enabled' : enabled + ' of ' + plural(PROJECTS.length, 'project') + ' enabled'); if (q.items.length) { const shown = q.items.slice(0, 5).map(row); // Keep five row slots so the card keeps its height when there are fewer items. while (shown.length < 5) shown.push(h('div', { class: 'row slot', 'aria-hidden': 'true' }, h('span', { class: 'src' }), h('span', null, h('span', { class: 'row-title', text: '\u00a0' }), h('span', { class: 'row-meta' }, h('span', { text: '\u00a0' }))), h('span', { class: 'chip', text: '\u00a0' }))); fill($('#overview-queue'), [h('div', { class: 'list slots' }, shown), status]); } else { fill($('#overview-queue'), [ h('div', { class: 'empty' }, h('div', { class: 'bubble' }, icon('inbox')), h('h3', { text: 'Your queue is clear' }), h('p', { text: 'Add some work to start building momentum.' }), h('button', { type: 'button', class: 'btn primary', 'data-open-create': '' }, icon('plus'), 'Add work')), flowDiagram(), h('h3', { style: 'margin-top:24px', text: "Know what's happening" }), status]); setupCreateButtons(); } const counts = [0, 0, 0, 0, 0]; for (const i of q.items) counts[i.priority == null ? 4 : i.priority]++; const max = Math.max.apply(null, counts) || 1; fill($('#prio'), q.items.length ? counts.map((n, i) => h('div', { class: 'bar-row' }, h('span', { text: i < 4 ? 'P' + i : 'Not set' }), h('div', { class: 'bar', role: 'img', 'aria-label': n + ' items' }, h('i', { style: 'width:' + (n / max * 100) + '%;background:' + (PRIO_COLORS[i] || 'var(--dot-off)') })), h('b', { text: String(n) }))) : [h('p', { class: 'muted', text: 'No open work to prioritize yet. Priorities show up here as work arrives.' })]); // Stalled section: top 5 stalled items/plans from board data var stalledSection = $('#overview-stalled-section'); var stalledBox = $('#overview-stalled'); if (stalledSection && stalledBox && d.board) { var stalledItems = []; var wCols = d.board.work.columns || {}; for (var wk in wCols) { (wCols[wk] || []).forEach(function(c) { if (c.stalled && c.column !== 'shipped' && c.column !== 'dropped') stalledItems.push(c); }); } var pCols = d.board.plans ? d.board.plans.columns || {} : {}; for (var pk in pCols) { (pCols[pk] || []).forEach(function(c) { if (c.stalled && c.column !== 'shipped') stalledItems.push(c); }); } stalledItems.sort(function(a, b) { return b.stalledBy - a.stalledBy; }); stalledItems = stalledItems.slice(0, 5); if (stalledItems.length) { stalledSection.hidden = false; fill(stalledBox, h('ul', { class: 'stalled-list' }, stalledItems.map(function(si) { var colLabel = BOARD_COL_LABELS[si.column] || PLAN_COL_LABELS[si.column] || si.column; return h('li', { class: 'stalled-row' }, h('div', null, h('div', { class: 'stalled-title', text: si.title }), h('div', { class: 'stalled-hint', text: colLabel + ' for ' + fmtAge(si.ageMs) + ' (limit ' + fmtAge(si.limitMs) + ')' })), h('span', { class: 'stalled-age', text: fmtAge(si.stalledBy) + ' over' })); }))); } else { stalledSection.hidden = true; } } const sorted = PROJECTS.slice().sort((a, b) => Number(b.enabled) - Number(a.enabled)); fill($('#overview-projects'), sorted.slice(0, 3).map((p) => projectCard(p))); $('#projects-link').textContent = 'View all ' + PROJECTS.length; footer(); } } function setupCreateButtons() { $$('#overview-queue [data-open-create]').forEach((b) => b.addEventListener('click', () => $('.hero [data-open-create]').click())); } async function renderWork() { const params = new URLSearchParams(location.search); const st = { q: params.get('q') || '', project: params.get('project') || '', status: params.get('status') || 'all' }; const search = $('#work-search'), sel = $('#work-project'), list = $('#work-list'), count = $('#work-count'); let items = [], total = 0; const sync = () => { const p = new URLSearchParams(); if (st.q) p.set('q', st.q); if (st.project) p.set('project', st.project); if (st.status !== 'all') p.set('status', st.status); history.replaceState(null, '', location.pathname + (p.toString() ? '?' + p : '')); }; const match = (i) => { if (st.project && i.projectId !== st.project) return false; const done = TERMINAL.indexOf(i.state) >= 0; if (st.status === 'active' && (done || i.state === 'needs-kent')) return false; if (st.status === 'needs' && i.state !== 'needs-kent' && !(i.needsKent && !done)) return false; if (st.status === 'complete' && !done) return false; if (st.q) { const hay = (i.title + ' ' + i.body + ' ' + i.projectId + ' ' + (i.repoRef || '') + ' ' + i.id).toLowerCase(); if (hay.indexOf(st.q.toLowerCase()) < 0) return false; } return true; }; const draw = () => { $$('.tabs button').forEach((b) => b.setAttribute('aria-pressed', String(b.dataset.status === st.status))); const shown = items.filter(match); count.textContent = 'Showing ' + plural(shown.length, 'item') + (total > items.length ? ' · first ' + items.length + ' of ' + total + ' loaded' : ''); if (shown.length) fill(list, shown.map(row)); else fill(list, h('div', { class: 'empty', style: 'padding:40px 16px' }, h('div', { class: 'bubble' }, icon('inbox')), h('h3', { text: items.length ? 'Nothing matches these filters' : 'Your queue is clear' }), h('p', { text: items.length ? 'Try another status or clear your search.' : 'Add some work to start building momentum.' }))); }; search.value = st.q; search.addEventListener('input', () => { st.q = search.value.trim(); sync(); draw(); }); sel.addEventListener('change', () => { st.project = sel.value; sync(); draw(); }); $$('.tabs button').forEach((b) => b.addEventListener('click', () => { st.status = b.dataset.status; sync(); draw(); })); document.addEventListener('keydown', (e) => { if (e.key === '/' && !/INPUT|TEXTAREA|SELECT/.test(document.activeElement.tagName) && !$('dialog[open]')) { e.preventDefault(); search.focus(); } }); let highlighted = false; try { await withData((d) => { const all = allWork(d); items = all.items; total = all.total; fill(sel, [h('option', { value: '', text: 'All projects' })].concat(PROJECTS.map((p) => h('option', { value: p.id, selected: p.id === st.project, text: p.displayName })))); draw(); footer(); const opened = params.get('card'); const created = params.get('created') || opened; if (created && !highlighted) { highlighted = true; const el = list.querySelector('[data-id="' + CSS.escape(created) + '"]'); if (el) { el.classList.add('flash-row'); el.focus(); el.scrollIntoView({ block: 'center' }); if (opened) el.click(); } else if (opened) openCardById(opened); params.delete('created'); params.delete('card'); sync(); } }); } catch (e) { count.textContent = ''; fill(list, errorBox(e.message)); } } async function renderProjects() { const grid = $('#projects-grid'), search = $('#project-search'); let draw = () => {}; search.addEventListener('input', () => draw()); try { await withData((d) => { const q = d.queue; fill($('#projects-banner'), []); const off = PROJECTS.filter((p) => !p.enabled).length; if (off) fill($('#projects-banner'), h('div', { class: 'notice' }, icon('alert'), h('div', null, h('strong', { text: plural(off, 'project') + (off === 1 ? ' is' : ' are') + ' disabled.' }), h('p', null, "The factory won't accept or advance work for disabled projects. ", h('a', { href: url('/manage'), text: 'Manage projects' }))))); draw = () => { const term = search.value.trim().toLowerCase(); const shown = PROJECTS.filter((p) => !term || (p.displayName + ' ' + p.id + ' ' + p.repos.map((r) => r.repoRef).join(' ')).toLowerCase().indexOf(term) >= 0); var boardWork = d.board ? d.board.work.columns : {}; var allItems = q.items.concat(d.finished ? d.finished.items : []); fill(grid, shown.length ? shown.map((p) => { const mine = allItems.filter((i) => i.projectId === p.id); const openMine = q.items.filter((i) => i.projectId === p.id); const needs = openMine.filter((i) => i.state === 'needs-kent').length; var stalledN = 0; for (var bk in boardWork) (boardWork[bk] || []).forEach(function(c) { if (c.projectId === p.id && c.stalled && c.column !== 'shipped' && c.column !== 'dropped') stalledN++; }); const openPrs = openMine.filter((i) => i.pr && !i.pr.merged).length; // 14-day activity sparkline from events var now14 = Date.now(), sparkData = []; for (var sd = 13; sd >= 0; sd--) { var dayStart = new Date(now14 - sd * 86400000).toISOString().slice(0, 10); var dayCount = 0; for (var si2 = 0; si2 < mine.length; si2++) { for (var ei2 = 0; ei2 < (mine[si2].events || []).length; ei2++) { var ev = mine[si2].events[ei2]; if (ev.at && ev.at.slice(0, 10) === dayStart && ev.from !== ev.to) dayCount++; } } sparkData.push({ v: dayCount, label: dayStart }); } // Last activity time var lastAct = null; for (var la = 0; la < mine.length; la++) { if (!lastAct || mine[la].updatedAt > lastAct) lastAct = mine[la].updatedAt; } // Main CI from postMerge/pr data only (no GitHub calls on list) var ciChip = null; for (var ci3 = 0; ci3 < mine.length; ci3++) { if (mine[ci3].postMerge && mine[ci3].postMerge.phase === 'watching') ciChip = h('span', { class: 'chip warn', text: 'Watching main' }); if (mine[ci3].postMerge && mine[ci3].postMerge.phase === 'implementer-notified') ciChip = h('span', { class: 'chip warn', text: 'Main red' }); } const card = projectCard(p, openMine.length, needs); const pmeta = card.querySelector('.pmeta'); if (pmeta) { var health = h('div', { class: 'pd-row-sub', style: 'margin-top:4px;display:flex;align-items:center;gap:6px;flex-wrap:wrap' }); if (mine.length === 0) { health.append(h('span', { class: 'muted small', text: 'No factory activity yet' })); } else { health.append(sparkline(sparkData, { width: 70, height: 18 })); if (lastAct) health.append(h('span', { class: 'muted small', text: age(lastAct) })); if (stalledN) health.append(h('span', { class: 'chip warn', text: stalledN + ' stalled' })); if (openPrs) health.append(h('span', { class: 'chip', text: openPrs + ' open PR' + (openPrs > 1 ? 's' : '') })); if (ciChip) health.append(ciChip); } pmeta.before(health); } return card; }) : h('p', { class: 'muted', text: PROJECTS.length ? 'No projects match your search.' : 'No projects yet. Add one in Manage projects.' })); }; draw(); if (q.total > q.items.length) $('#projects-banner').append(h('p', { class: 'muted small', text: 'Counts use the first ' + q.items.length + ' of ' + q.total + ' open items.' })); footer(); }); } catch (e) { fill(grid, errorBox(e.message)); } } function kv(title, desc, chip, cls) { return h('li', null, h('div', null, h('b', { text: title }), h('span', { class: 'd', text: desc })), h('span', { class: 'chip ' + (cls || ''), text: chip })); } async function renderSettings() { try { await withData((d) => { var s = d.snapshot; var p = s.policy; var ks = d.settings && d.settings.killSwitch; fill($('#run-safely'), h('ul', { class: 'kv' }, p.shadowMode ? kv('Shadow mode', 'New work stays parked before an agent session starts.', 'Observation only', 'warn') : kv('Shadow mode', 'Agent sessions can start for ready work.', 'Off', 'on'), kv('Max concurrent sessions', 'Up to ' + p.maxConcurrentRuns + ' agent sessions at a time.', String(p.maxConcurrentRuns)), kv('Merge policy', p.agentMayMerge === 'none' ? 'Every merge stays with you.' : 'Agent merge policy: ' + p.agentMayMerge, p.agentMayMerge === 'none' ? "Agents can't merge" : 'Agents may merge', p.agentMayMerge === 'none' ? 'on' : 'warn'), kv('Sweep', 'Every 15 minutes. Moves each item at most one stage per run.', s.jobsEnabled ? 'Scheduled' : 'Off', s.jobsEnabled ? 'on' : 'off'), (function () { var sc = p.pilotScope || { mode: 'allowlist', projectIds: [] }; var none = sc.mode !== 'all' && !sc.projectIds.length; return kv('Pilot scope', none ? 'Sweep, backfill, and issue intake act on no project until a pilot scope is set.' : sc.mode === 'all' ? 'Every enabled project.' : 'Only ' + sc.projectIds.join(', ') + (sc.repoRefs && sc.repoRefs.length ? ' (' + sc.repoRefs.join(', ') + ')' : '') + '.', none ? 'Not set' : sc.mode === 'all' ? 'All projects' : 'Pilot', none ? 'warn' : 'on'); })())); var rc = s.runnerConfig; fill($('#connections'), h('ul', { class: 'kv' }, kv('Devin', 'Agent runner for building work, reached through @kody/' + ((rc.runners && rc.runners.devin && rc.runners.devin.package) || 'devin') + ' events.', 'Events', 'on'), kv('Cloudflare AI', 'Model used to triage new work.', rc.cloudflareAccountIdSet ? 'Account configured' : 'Not configured', rc.cloudflareAccountIdSet ? 'on' : 'warn'), kv('GitHub intake', 'Issue and CI webhooks are declared and need your approval before events arrive.', 'Setup required', 'warn'), kv('GitHub issue backfill', 'Preview open issues from enabled repositories, then add them in shadow mode. Runs only when you ask.', 'On demand', 'off'), kv('Plans', s.planning && s.planning.status === 'factory-native' ? 'Plans live in the factory. GitHub Projects import is available.' : 'Planning board updates are turned off.', s.planning && s.planning.status === 'factory-native' ? 'Factory native' : 'Not connected', s.planning && s.planning.status === 'factory-native' ? 'on' : 'off'))); updateKillSwitch(ks); setupConfigUI(); setupTemplatesUI(); setupPushUI(); footer(); }); } catch (e) { fill($('#run-safely'), errorBox(e.message)); fill($('#connections'), []); } } function b64urlToBytes(t) { var pad = '='.repeat((4 - (t.length % 4)) % 4); var bin = atob(t.replace(/-/g, '+').replace(/_/g, '/') + pad); var out = new Uint8Array(bin.length); for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); return out; } function deviceLabel() { var ua = navigator.userAgent || ''; var os = /iPhone|iPad/.test(ua) ? 'iOS' : /Android/.test(ua) ? 'Android' : /Mac/.test(ua) ? 'macOS' : /Windows/.test(ua) ? 'Windows' : /Linux/.test(ua) ? 'Linux' : 'Device'; var br = /Edg\//.test(ua) ? 'Edge' : /Firefox\//.test(ua) ? 'Firefox' : /Chrome\//.test(ua) ? 'Chrome' : /Safari\//.test(ua) ? 'Safari' : 'Browser'; return br + ' on ' + os; } async function pushPost(path, body) { var r = await fetch(url(path), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}) }); var d = await r.json().catch(function () { return {}; }); if (!r.ok) throw new Error(d.error || (d.errors && d.errors[0]) || d.skipped || ('HTTP ' + r.status)); return d; } async function setupPushUI() { var status = $('#push-status'), list = $('#push-devices'), en = $('#push-enable'), test = $('#push-test'), off = $('#push-disable'); if (!status) return; var supported = 'serviceWorker' in navigator && 'PushManager' in window && 'Notification' in window; async function refresh() { var info; try { var r = await fetch(url('/api/push'), { headers: { accept: 'application/json' } }); info = await r.json(); if (!r.ok) throw new Error(info.error || ('HTTP ' + r.status)); } catch (e) { status.textContent = 'Push status unavailable: ' + e.message; en.hidden = test.hidden = off.hidden = true; return; } var reg = supported ? await navigator.serviceWorker.getRegistration(BP + '/') : null; var sub = reg ? await reg.pushManager.getSubscription() : null; fill(list, (info.devices || []).map(function (dv) { return kv(dv.label, dv.host + (dv.lastError ? ' · last error: ' + dv.lastError : dv.lastOkAt ? ' · last delivered ' + fmtFull(dv.lastOkAt) : ''), dv.lastError ? 'Failing' : 'On', dv.lastError ? 'warn' : 'on'); })); if (!info.configured) { status.textContent = 'Web push is not configured on the server yet.'; en.hidden = test.hidden = off.hidden = true; return; } if (!supported) { status.textContent = 'This browser does not support web push. On iPhone, add the factory to your Home Screen first.'; en.hidden = true; test.hidden = !(info.devices || []).length; off.hidden = true; return; } var perm = Notification.permission; if (perm === 'denied') status.textContent = 'Notifications are blocked for this site in your browser settings.'; else if (sub) status.textContent = 'This device gets push notifications.'; else status.textContent = 'This device is not subscribed.'; en.hidden = !!sub || perm === 'denied'; off.hidden = !sub; test.hidden = !(info.devices || []).length; en.onclick = async function () { en.disabled = true; try { var p = await Notification.requestPermission(); if (p !== 'granted') throw new Error('Permission was not granted'); var r2 = reg || await navigator.serviceWorker.register(url('/sw.js'), { scope: BP + '/', updateViaCache: 'none' }); await navigator.serviceWorker.ready; var s2 = await r2.pushManager.subscribe({ userVisibleOnly: true, applicationServerKey: b64urlToBytes(info.publicKey) }); await pushPost('/api/push/subscribe', { subscription: s2.toJSON(), label: deviceLabel() }); toast('Push is on for this device.'); } catch (e) { toast('Could not turn on push: ' + e.message); } en.disabled = false; refresh(); }; off.onclick = async function () { off.disabled = true; try { if (sub) { await pushPost('/api/push/unsubscribe', { endpoint: sub.endpoint }); await sub.unsubscribe(); } toast('Push is off for this device.'); } catch (e) { toast('Could not turn off push: ' + e.message); } off.disabled = false; refresh(); }; test.onclick = async function () { test.disabled = true; try { var d = await pushPost('/api/push/test', {}); toast(d.sent ? 'Test push sent to ' + plural(d.sent, 'device') + '.' : (d.skipped || 'Nothing was sent.')); } catch (e) { toast('Test push failed: ' + e.message); } test.disabled = false; refresh(); }; } refresh(); } function updateKillSwitchBanner(on) { var banner = $('#kill-switch-banner'); if (banner) banner.hidden = !on; } function updateKillSwitch(on) { updateKillSwitchBanner(on); var btn = $('#kill-switch-toggle'); if (!btn) return; btn.textContent = on ? 'Disengage kill switch' : 'Engage kill switch'; btn.className = 'btn' + (on ? ' warn' : ''); btn.onclick = async function() { btn.disabled = true; btn.textContent = 'Saving...'; try { var r = await fetch(url('/api/config/import'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ doc: { version: 1, exportedAt: '', projects: [], settings: { shadowMode: false, maxConcurrentRuns: 3, agentMayMerge: 'none', sweepStartLimit: 3, agentDryRunDefault: false, killSwitch: !on, postMergeFixTimeoutMinutes: 60, postMergePendingTimeoutMinutes: 180, stallHealthEnabled: false }, jobs: [], credentialNeeds: [] }, apply: true }) }); if (r.ok) { invalidateData(); toast(on ? 'Kill switch disengaged. The factory will resume normal operation.' : 'Kill switch engaged. No new agent runs or merges will start.'); updateKillSwitch(!on); } else { var d = await r.json().catch(function() { return {}; }); toast('Error: ' + (d.error || 'Could not update')); } } catch (e) { toast('Error: ' + e.message); } btn.disabled = false; }; } function setupConfigUI() { var exportBtn = $('#config-export-btn'); if (exportBtn) exportBtn.addEventListener('click', async function() { exportBtn.disabled = true; exportBtn.textContent = 'Exporting...'; try { var r = await getJson('/api/config/export'); var blob = new Blob([JSON.stringify(r, null, 2)], { type: 'application/json' }); var a = document.createElement('a'); a.href = URL.createObjectURL(blob); a.download = 'kody-factory-config-' + new Date().toISOString().slice(0, 10) + '.json'; a.click(); URL.revokeObjectURL(a.href); toast('Config exported.'); } catch (e) { toast('Export failed: ' + e.message); } exportBtn.disabled = false; exportBtn.textContent = 'Export config'; }); var fileInput = $('#config-import-file'); var previewEl = $('#config-import-preview'); if (fileInput) fileInput.addEventListener('change', async function(ev) { var file = ev.target.files[0]; if (!file) return; try { var text = await file.text(); var doc = JSON.parse(text); previewEl.hidden = false; fill(previewEl, h('p', { class: 'muted small', text: 'Checking...' })); var r = await fetch(url('/api/config/import'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ doc: doc }) }); var preview = await r.json(); if (!preview.valid) { fill(previewEl, h('div', { class: 'flash bad' }, h('strong', { text: 'Invalid config' }), h('ul', null, (preview.errors || []).map(function(e) { return h('li', { text: e }); })))); return; } if (preview.isEmpty) { fill(previewEl, h('div', { class: 'flash' }, h('strong', { text: 'No changes' }), h('p', { class: 'small', text: 'This config matches the current configuration.' }))); return; } var d = preview.diff; var lines = []; (d.settings || []).forEach(function(c) { lines.push('Setting ' + c.key + ': ' + JSON.stringify(c.from) + ' -> ' + JSON.stringify(c.to)); }); (d.projects.added || []).forEach(function(id) { lines.push('Add project: ' + id); }); (d.projects.removed || []).forEach(function(id) { lines.push('Would remove project: ' + id + ' (not removed unless confirmed)'); }); (d.projects.changed || []).forEach(function(ch) { ch.changes.forEach(function(c) { lines.push('Project ' + ch.id + ' ' + c.key + ': change'); }); }); (d.jobs || []).forEach(function(j) { lines.push('Job ' + j.name + ': ' + (j.from ? 'enabled' : 'disabled') + ' -> ' + (j.to ? 'enabled' : 'disabled')); }); var applyBtn = h('button', { type: 'button', class: 'btn primary', text: 'Apply changes' }); applyBtn.addEventListener('click', async function() { applyBtn.disabled = true; applyBtn.textContent = 'Applying...'; try { var ar = await fetch(url('/api/config/import'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ doc: doc, apply: true }) }); var result = await ar.json(); if (result.applied) { invalidateData(); toast('Config imported. ' + (result.settingsUpdated || []).length + ' settings and ' + ((result.projectsAdded || []).length + (result.projectsUpdated || []).length) + ' projects updated.'); previewEl.hidden = true; if (RENDER) RENDER(); } else { toast('Import failed: ' + ((result.errors || []).join(', ') || 'unknown error')); } } catch (e) { toast('Import failed: ' + e.message); } applyBtn.disabled = false; applyBtn.textContent = 'Apply changes'; }); fill(previewEl, [ h('h3', { text: 'Preview changes' }), h('ul', { class: 'kv' }, lines.map(function(l) { return h('li', null, h('div', null, h('b', { text: l }))); })), h('div', { class: 'row-btns', style: 'margin-top:12px' }, applyBtn) ]); } catch (e) { fill(previewEl, h('div', { class: 'flash bad', text: 'Could not read file: ' + e.message })); } fileInput.value = ''; }); } function setupTemplatesUI() { var container = $('#templates-list'); if (!container) return; getJson('/api/config/templates').then(function(data) { var templates = data.templates || []; if (!templates.length) { fill(container, h('p', { class: 'muted', text: 'No templates available.' })); return; } fill(container, templates.map(function(t) { var applyBtn = h('button', { type: 'button', class: 'btn', text: 'Preview' }); applyBtn.addEventListener('click', async function() { applyBtn.disabled = true; applyBtn.textContent = 'Loading...'; try { var r = await fetch(url('/api/config/templates/apply'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ templateId: t.id }) }); var preview = await r.json(); if (preview.isEmpty) { toast('This template matches the current config. No changes needed.'); applyBtn.disabled = false; applyBtn.textContent = 'Preview'; return; } var d = preview.diff || {}; var lines = []; (d.settings || []).forEach(function(c) { lines.push('Setting ' + c.key + ': ' + JSON.stringify(c.from) + ' -> ' + JSON.stringify(c.to)); }); (d.projects && d.projects.added || []).forEach(function(id) { lines.push('Add project: ' + id); }); (d.projects && d.projects.changed || []).forEach(function(ch) { ch.changes.forEach(function(c) { lines.push('Project ' + ch.id + ' ' + c.key + ': change'); }); }); var dlg = $('#confirm-dialog'); $('#confirm-title').textContent = 'Apply template: ' + t.name + '?'; fill($('#confirm-text'), lines.length ? h('ul', null, lines.map(function(l) { return h('li', { text: l }); })) : 'No changes detected.'); $('#confirm-ok').textContent = 'Apply'; var okBtn = $('#confirm-ok'); var handler = async function() { okBtn.removeEventListener('click', handler); dlg.close(); try { var ar = await fetch(url('/api/config/templates/apply'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ templateId: t.id, apply: true }) }); var result = await ar.json(); if (result.applied) { invalidateData(); toast('Template "' + t.name + '" applied.'); if (RENDER) RENDER(); } else { toast('Could not apply template.'); } } catch (e) { toast('Error: ' + e.message); } }; okBtn.addEventListener('click', handler); dlg.showModal(); } catch (e) { toast('Error: ' + e.message); } applyBtn.disabled = false; applyBtn.textContent = 'Preview'; }); return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main', style: 'min-width:0' }, h('div', { class: 'pd-row-title', text: t.name }), h('div', { class: 'pd-row-sub', text: t.description })), h('div', { class: 'pd-row-side' }, applyBtn)); })); }).catch(function(e) { fill(container, h('p', { class: 'muted', text: 'Could not load templates.' })); }); } function setupManage() { const dlg = $('#confirm-dialog'); let pending = null; $$('form[data-confirm]').forEach((f) => f.addEventListener('submit', (ev) => { ev.preventDefault(); pending = f; $('#confirm-title').textContent = f.querySelector('button').textContent.trim() + '?'; $('#confirm-text').textContent = f.dataset.confirm; $('#confirm-ok').textContent = f.querySelector('button').textContent.trim(); dlg.showModal(); })); $('#confirm-ok').addEventListener('click', () => { if (pending) pending.submit(); }); const bf = $('#backfill-form'); if (bf) { const out = $('#backfill-result'), ingest = $('#backfill-ingest'), preview = bf.querySelector('[type=submit]'); let last = null; const params = () => ({ projectId: bf.elements.projectId.value || undefined, perRepoLimit: Number(bf.elements.perRepoLimit.value) || 30 }); const run = async (dryRun) => { const r = await fetch(url('/api/sync'), { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify(Object.assign(params(), { dryRun: dryRun })) }); const d = await r.json().catch(() => null); if (!d) throw new Error('The backfill did not return a report (' + r.status + ').'); return d; }; const report = (d) => { const t = d.totals; const nodes = []; if (d.setup) nodes.push(h('div', { class: 'flash bad' }, h('strong', { text: 'GitHub is not connected.' }), h('div', { class: 'small', style: 'margin-top:6px;font-weight:400', text: d.message }))); else if (d.message) nodes.push(h('p', { class: 'muted small', text: d.message })); nodes.push(h('p', { class: 'small' }, (d.dryRun ? 'Preview: ' : 'Added: ') + plural(t.eligible, 'eligible issue') + ' · ' + t.alreadyQueued + ' already queued · ' + t.skippedPullRequests + ' pull requests skipped · ' + plural(t.repos, 'repository', 'repositories') + ' read' + (d.dryRun ? '' : ' · ' + plural(t.created, 'item') + ' created'))); d.repos.filter((r) => r.error).forEach((r) => nodes.push(h('p', { class: 'small err', text: r.repoRef + ': ' + r.error }))); d.skippedRepos.forEach((r) => nodes.push(h('p', { class: 'small muted', text: r.repoRef + ' skipped: ' + r.reason }))); if (d.issues.length) nodes.push(h('ul', { class: 'kv' }, d.issues.slice(0, 100).map((i) => h('li', null, h('div', null, h('b', null, i.url ? h('a', { href: i.url, target: '_blank', rel: 'noopener noreferrer', text: i.title }) : i.title), h('span', { class: 'd', text: i.repoRef + ' #' + i.number + (i.priority != null ? ' · P' + i.priority : '') + (i.needsKent ? ' · Needs you' : '') })), h('span', { class: 'chip ' + (i.status === 'eligible' ? 'on' : 'off'), text: i.status === 'eligible' ? (d.dryRun ? 'Eligible' : 'Added') : 'Already queued' }))))); fill(out, nodes); }; bf.addEventListener('submit', async (ev) => { ev.preventDefault(); ingest.hidden = true; last = null; preview.disabled = true; preview.textContent = 'Reading GitHub…'; try { const d = await run(true); last = d; report(d); ingest.hidden = !(d.ok && d.totals.eligible > 0); if (!ingest.hidden) ingest.textContent = 'Add ' + plural(d.totals.eligible, 'eligible issue') + ' as New'; } catch (e) { fill(out, h('div', { class: 'flash bad', text: e.message })); } preview.disabled = navigator.onLine === false; preview.textContent = 'Preview issues'; }); bf.addEventListener('input', () => { ingest.hidden = true; last = null; }); ingest.addEventListener('click', () => { if (!last) return; pending = { submit: async () => { dlg.close(); ingest.disabled = true; ingest.textContent = 'Adding…'; try { const d = await run(false); report(d); invalidateData(); } catch (e) { fill(out, h('div', { class: 'flash bad', text: e.message })); } ingest.hidden = true; ingest.disabled = false; last = null; } }; $('#confirm-title').textContent = 'Add ' + plural(last.totals.eligible, 'issue') + ' to the queue?'; $('#confirm-text').textContent = 'They join as New in shadow mode. Nothing is triaged, planned, or started by this. GitHub is only read.'; $('#confirm-ok').textContent = 'Add issues'; dlg.showModal(); }); } const smoke = $('#smoke-form'); if (smoke) smoke.addEventListener('submit', async (ev) => { ev.preventDefault(); const out = $('#smoke-result'), btn = smoke.querySelector('button'); btn.disabled = true; btn.textContent = 'Checking…'; fill(out, []); try { const r = await fetch(smoke.action, { method: 'POST', body: new URLSearchParams(new FormData(smoke)), headers: { accept: 'application/json' } }); const ct = r.headers.get('content-type') || ''; if (!ct.includes('json')) throw new Error(new URL(r.url).searchParams.get('flash') || 'The check did not return a result.'); const d = await r.json(); fill(out, h('div', { class: d.modelUsed ? 'flash' : 'flash bad' }, h('strong', { text: d.modelUsed ? 'The model responded.' : 'The model was not used; triage fell back to rules.' }), h('div', { class: 'small', style: 'margin-top:6px;font-weight:400' }, 'Decision: ' + d.decision + (d.reason ? ' · ' + d.reason : '')))); } catch (e) { fill(out, h('div', { class: 'flash bad', text: e.message })); } btn.disabled = false; btn.textContent = 'Check model connection'; }); } function footer() { if (PROJECTS.length) $('#configured-for').textContent = 'Configured for ' + plural(PROJECTS.length, 'project'); } $$('dialog').forEach((d) => { d.addEventListener('click', (e) => { if (e.target === d) d.close(); }); $$('[data-close]', d).forEach((b) => b.addEventListener('click', () => d.close())); }); const THEME_KEY = 'kody-factory-theme'; const THEME_NAMES = { light: 'Light', dark: 'Dark', system: 'System' }; const darkQuery = window.matchMedia ? matchMedia('(prefers-color-scheme: dark)') : null; function readTheme() { try { const v = localStorage.getItem(THEME_KEY); return v === 'light' || v === 'dark' ? v : 'system'; } catch (e) { return 'system'; } } function applyTheme(pref) { const eff = pref === 'system' ? (darkQuery && darkQuery.matches ? 'dark' : 'light') : pref; const root = document.documentElement; root.setAttribute('data-theme', eff); root.setAttribute('data-theme-pref', pref); root.style.colorScheme = eff; const desc = 'Theme: ' + THEME_NAMES[pref] + (pref === 'system' ? ' (currently ' + eff + ')' : ''); const btn = $('#theme-btn'); if (btn) { btn.title = desc; btn.setAttribute('aria-label', desc + '. Change theme'); } $$('input[data-theme-choice]').forEach((i) => { i.checked = i.value === pref; }); } function setupTheme() { const btn = $('#theme-btn'), menu = $('#theme-menu'); applyTheme(readTheme()); $$('input[data-theme-choice]').forEach((i) => i.addEventListener('change', () => { if (!i.checked) return; try { localStorage.setItem(THEME_KEY, i.value); } catch (e) {} applyTheme(i.value); })); if (darkQuery) darkQuery.addEventListener('change', () => { if (readTheme() === 'system') applyTheme('system'); }); window.addEventListener('storage', (e) => { if (e.key === THEME_KEY) applyTheme(readTheme()); }); if (!btn || !menu) return; const close = (focus) => { menu.hidden = true; btn.setAttribute('aria-expanded', 'false'); if (focus) btn.focus(); }; btn.addEventListener('click', () => { if (!menu.hidden) return close(false); menu.hidden = false; btn.setAttribute('aria-expanded', 'true'); const cur = menu.querySelector('input:checked') || menu.querySelector('input'); if (cur) cur.focus(); }); menu.addEventListener('keydown', (e) => { if (e.key === 'Escape') { e.preventDefault(); close(true); } }); document.addEventListener('click', (e) => { if (!menu.hidden && !$('#theme').contains(e.target)) close(false); }); $('#theme').addEventListener('focusout', (e) => { if (!menu.hidden && e.relatedTarget && !$('#theme').contains(e.relatedTarget)) close(false); }); } // Board categories var CATEGORY_LABELS = { plan: 'Plan', 'github-issue': 'GitHub issue', friction: 'Friction', sentry: 'Sentry', discord: 'Discord', cleanup: 'Cleanup', 'ship-pr': 'Ship PR', generic: 'Generic' }; var CATEGORY_COLORS = { plan: '#6d28d9', 'github-issue': '#334155', friction: '#b45309', sentry: '#6d28d9', discord: '#4338ca', cleanup: '#15803d', 'ship-pr': '#0f766e', generic: '#475569' }; var ALL_CATEGORIES = ['plan', 'github-issue', 'friction', 'sentry', 'discord', 'cleanup', 'ship-pr', 'generic']; function categoryChip(cat) { return h('span', { class: 'chip cat-chip', style: '--cat-c:' + (CATEGORY_COLORS[cat] || '#475569'), text: CATEGORY_LABELS[cat] || cat }); } // Board view const BOARD_COL_LABELS = { intake: 'Intake', triaged: 'Triaged', planned: 'Planned', running: 'Running', 'in-review': 'In review', 'watching-main': 'Watching main', shipped: 'Shipped', 'needs-kent': 'Needs Kent', dropped: 'Dropped' }; const BOARD_COLS = ['intake','triaged','planned','running','in-review','watching-main','shipped','needs-kent','dropped']; const PLAN_COL_LABELS = { exploring: 'Exploring', proposed: 'Proposed', decided: 'Decided', 'in-progress': 'In progress', shipped: 'Shipped' }; const PLAN_COLS = ['exploring','proposed','decided','in-progress','shipped']; const SUB_LABELS = { waiting: 'Waiting', needs_attention: 'Needs attention', action_available: 'Action available', ready_to_merge: 'Ready to merge', done: 'Done', blocked: 'Blocked' }; function fmtAge(ms) { if (ms < 60000) return 'just now'; var m = Math.floor(ms / 60000); if (m < 60) return m + 'm'; var hr = Math.floor(m / 60), rm = m % 60; if (hr < 24) return rm ? hr + 'h ' + rm + 'm' : hr + 'h'; var d = Math.floor(hr / 24), rh = hr % 24; return rh ? d + 'd ' + rh + 'h' : d + 'd'; } // Work board move rules (mirrors server-side validateMove) var WORK_VALID_MOVES = { intake: ['triaged', 'needs-kent', 'dropped'], triaged: ['planned', 'needs-kent', 'dropped'], planned: ['needs-kent', 'dropped'], 'needs-kent': ['intake', 'triaged', 'planned', 'dropped'], dropped: ['intake'] }; var PLAN_VALID_MOVES = { exploring: ['proposed', 'decided', 'shipped'], proposed: ['exploring', 'decided', 'in-progress', 'shipped'], decided: ['exploring', 'proposed', 'in-progress', 'shipped'], 'in-progress': ['decided', 'shipped'] }; function canMove(from, to, kind) { if (from === to) return false; var map = kind === 'plan' ? PLAN_VALID_MOVES : WORK_VALID_MOVES; var allowed = map[from]; return allowed ? allowed.indexOf(to) >= 0 : false; } async function postMove(kind, id, to, reason) { var r = await fetch(url('/api/move-card'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ kind: kind, id: id, to: to, reason: reason, actor: 'human' }) }); return r.json(); } // Safe mini-markdown for plan body (HTML-escaped first, then formatted) function renderMd(raw) { if (!raw) return ''; var s = raw.replace(/&/g, '&').replace(//g, '>').replace(/"/g, '"'); var BT = String.fromCharCode(96); var btRe = new RegExp(BT + '([^' + BT + ']+)' + BT, 'g'); function fmt(ln) { ln = ln.replace(btRe, '$1'); ln = ln.replace(/[*][*]([^*]+)[*][*]/g, '$1'); ln = ln.replace(/[*]([^*]+)[*]/g, '$1'); ln = ln.replace(/\[([^\]]+)\]\(([^)]+)\)/g, function(_m, t, hr) { var decoded = hr.replace(/&/g, '&'); if (/^https?:\/\//i.test(decoded)) return '' + t + ''; return t + ' (' + hr + ')'; }); return ln; } var fence = BT + BT + BT; var lines = s.split('\n'), out = [], i = 0; while (i < lines.length) { var ln = lines[i]; if (ln.indexOf(fence) === 0) { var cl = []; i++; while (i < lines.length && lines[i].indexOf(fence) !== 0) { cl.push(lines[i]); i++; } if (i < lines.length) i++; out.push('
' + cl.join('\n') + '
'); continue; } if (/^### /.test(ln)) { out.push('

' + fmt(ln.slice(4)) + '

'); i++; continue; } if (/^## /.test(ln)) { out.push('

' + fmt(ln.slice(3)) + '

'); i++; continue; } if (/^# /.test(ln)) { out.push('

' + fmt(ln.slice(2)) + '

'); i++; continue; } if (/^> /.test(ln) || ln === '>') { var bq = []; while (i < lines.length && (/^> /.test(lines[i]) || lines[i] === '>')) { bq.push(lines[i].replace(/^> ?/, '')); i++; } out.push('
' + bq.map(fmt).join('
') + '
'); continue; } if (/^\s*[-*] /.test(ln)) { var ul = []; while (i < lines.length && /^\s*[-*] /.test(lines[i])) { var ct = lines[i].replace(/^\s*[-*] /, ''); var tc = /^\[x\] (.*)/i.exec(ct), tu = /^\[ \] (.*)/.exec(ct); if (tc) ul.push('
  • '); else if (tu) ul.push('
  • '); else ul.push('
  • ' + fmt(ct) + '
  • '); i++; } out.push(''); continue; } if (/^\d+\. /.test(ln)) { var ol = []; while (i < lines.length && /^\d+\. /.test(lines[i])) { ol.push('
  • ' + fmt(lines[i].replace(/^\d+\. /, '')) + '
  • '); i++; } out.push('
      ' + ol.join('') + '
    '); continue; } if (ln.trim() === '') { i++; continue; } out.push('

    ' + fmt(ln) + '

    '); i++; } return out.join('\n'); } // Column history timeline from events function colTimeline(events, currentColumn, currentEnteredAt, limitMs, colLabels) { if (!events || !events.length) return null; var segments = []; var prev = null; for (var ei = 0; ei < events.length; ei++) { var e = events[ei]; if (prev && prev.to === e.to) continue; if (prev) prev.endAt = e.at; prev = { col: e.to, startAt: e.at, endAt: null, reason: e.reason, actor: e.actor }; segments.push(prev); } var items = segments.map(function(seg) { var label = colLabels[seg.col] || (STATES[seg.col] || [seg.col])[0] || seg.col; var isCurrent = seg === segments[segments.length - 1]; var dur = seg.endAt ? Date.parse(seg.endAt) - Date.parse(seg.startAt) : Date.now() - Date.parse(seg.startAt); var durText = dur > 0 ? fmtAge(dur) : ''; var li = h('li', { class: 'tl-item' + (isCurrent ? ' current' : '') }, h('span', { class: 'tl-dot', 'aria-hidden': 'true' }), h('div', { class: 'tl-body' }, h('div', { class: 'tl-col', text: label }), h('div', { class: 'tl-when', text: fmtFull(seg.startAt) + (seg.actor ? ' by ' + seg.actor : '') }), durText ? h('div', { class: 'tl-dur', text: durText + (isCurrent && limitMs ? ' of ' + fmtAge(limitMs) + ' limit' : '') }) : null, seg.reason ? h('div', { class: 'tl-reason', text: seg.reason }) : null)); return li; }); return h('ul', { class: 'timeline' }, items); } function bcard(c) { var warmCls = c.stalled ? ' stalled' : (c.ageMs >= c.limitMs * 0.75 && c.limitMs > 0 ? ' warm' : ''); var ageCls = c.stalled ? ' over' : (c.ageMs >= c.limitMs * 0.75 && c.limitMs > 0 ? ' warn' : ''); var chips = []; if (c.priority != null) chips.push(h('span', { class: 'chip', text: 'P' + c.priority })); if (c.reviewSubstate && SUB_LABELS[c.reviewSubstate]) chips.push(h('span', { class: 'chip sub-' + c.reviewSubstate, text: SUB_LABELS[c.reviewSubstate] })); if (c.shipPr) chips.push(h('span', { class: 'chip sub-' + c.shipPr.status, text: (SUB_LABELS[c.shipPr.status] || c.shipPr.status) })); if (c.watchSubstate && c.watchSubstate !== 'watching') chips.push(h('span', { class: 'chip', text: c.watchSubstate.replace(/-/g, ' ') })); if (c.category) { var catEl = categoryChip(c.category); if (c.categoryConfirmed === false && c.categoryGuess) { catEl = h('span', { class: 'chip cat-chip cat-unconfirmed', style: '--cat-c:' + (CATEGORY_COLORS[c.category] || '#475569'), title: 'Unconfirmed guess from Clef' }, (CATEGORY_LABELS[c.category] || c.category), ' ', h('span', { class: 'cat-guess-badge', text: '?' })); } chips.unshift(catEl); } var card = h('div', { class: 'bcard' + warmCls, tabindex: '0', draggable: 'true', 'data-id': c.id, 'data-kind': c.kind || 'work', 'data-col': c.column, 'data-category': c.category || '', onclick: function() { if (c.kind === 'plan') openPlanCard(c); else openBoardItem(c); } }, h('div', { class: 'bcard-title', text: c.title }), h('div', { class: 'bcard-meta' }, h('span', { text: projectName(c.projectId) }), c.repoRef ? h('span', { class: 'repo', text: c.repoRef }) : null, c.prNumber ? h('a', { href: c.prUrl, target: '_blank', rel: 'noreferrer', text: '#' + c.prNumber, onclick: function(e) { e.stopPropagation(); } }) : null), chips.length ? h('div', { class: 'bcard-chips' }, chips) : null, h('div', { class: 'bcard-age' + ageCls }, icon('clock'), c.stalled ? fmtAge(c.ageMs) + ' in ' + (BOARD_COL_LABELS[c.column] || c.column) + ' (stalled)' : fmtAge(c.ageMs) + ' in ' + (BOARD_COL_LABELS[c.column] || c.column)), c.claimedBy ? h('div', { class: 'bcard-claim', text: 'Claimed by ' + c.claimedBy }) : null ); return card; } function planCard(c) { var warmCls = c.stalled ? ' stalled' : (c.ageMs >= c.limitMs * 0.75 && c.limitMs > 0 ? ' warm' : ''); var ageCls = c.stalled ? ' over' : (c.ageMs >= c.limitMs * 0.75 && c.limitMs > 0 ? ' warn' : ''); return h('div', { class: 'bcard' + warmCls, tabindex: '0', 'data-id': c.id, 'data-kind': 'plan', onclick: function() { openPlanCard(c); } }, h('div', { class: 'bcard-title', text: c.title }), h('div', { class: 'bcard-meta' }, h('span', { text: projectName(c.projectId) }), c.priority != null ? h('span', { class: 'prio', text: 'P' + c.priority }) : null, c.linkedWorkCount ? h('span', { text: c.linkedWorkCount + ' linked' }) : null), h('div', { class: 'bcard-age' + ageCls }, icon('clock'), c.stalled ? fmtAge(c.ageMs) + ' (stalled)' : fmtAge(c.ageMs)) ); } function openBoardItem(c) { withData(function(d) { var item = d.queue.items.concat(d.finished.items).find(function(i) { return i.id === c.id; }); if (!item) return; var dlg = $('#item-dialog'); var st = STATES[item.state] || [item.state, '']; var sess = sessionUrl(item); var dl = h('dl', { class: 'meta' }); var add = function(k, v) { if (v != null && v !== '') dl.append(h('dt', { text: k }), h('dd', null, v)); }; add('Project', projectName(item.projectId)); add('Source', sourceOf(item)[0]); add('Priority', item.priority != null ? 'P' + item.priority : 'Not set'); add('Added', fmtFull(item.createdAt)); add('Updated', fmtFull(item.updatedAt)); if (item.labels && item.labels.length) add('Labels', item.labels.join(', ')); add('ID', h('code', { text: item.id })); var tl = colTimeline(item.events, c.column, c.enteredColumnAt, c.limitMs, BOARD_COL_LABELS); fill($('#item-body'), [ h('div', { class: 'dlg-head' }, h('div', null, stateChip(item.state), h('h2', { id: 'item-title', style: 'margin-top:10px', text: item.title })), h('button', { type: 'button', class: 'icon-btn', 'aria-label': 'Close', onclick: function() { dlg.close(); } }, icon('close'))), h('p', { class: 'muted', text: st[1] }), item.body ? h('div', { class: 'body-text', text: item.body }) : null, dl, sess ? h('div', null, h('a', { class: 'btn', href: sess, target: '_blank', rel: 'noreferrer' }, icon('external'), 'Open Devin session')) : null, tl ? h('section', { class: 'stack' }, h('h3', { text: 'Column history' }), tl) : null ]); dlg.showModal(); }); } var PLAN_DETAIL_CACHE = {}; function openPlanCard(c) { withData(function(d) { if (!d.board || !d.board.plans) return; var dlg = $('#plan-dialog') || $('#item-dialog'); if (!dlg) return; var cols = d.board.plans.columns; var allPlans = []; for (var k in cols) if (cols[k]) allPlans = allPlans.concat(cols[k]); var plan = allPlans.find(function(p) { return p.id === c.id; }); if (!plan) return; var body = $('#plan-body') || $('#item-body'); var renderPlanDetail = function(fullPlan) { var rendered = fullPlan && fullPlan.body ? renderMd(fullPlan.body) : null; var bodyEl = null; if (rendered) { bodyEl = h('div', { class: 'plan-body-render' }); bodyEl.innerHTML = rendered; } else if (navigator.onLine === false) { bodyEl = h('p', { class: 'muted small', text: 'Plan body is not available offline.' }); } var notes = fullPlan && fullPlan.progressNotes && fullPlan.progressNotes.length ? h('section', { class: 'stack' }, h('h3', { text: 'Progress' }), h('ul', { class: 'plan-notes' }, fullPlan.progressNotes.slice().reverse().map(function(n) { return h('li', null, h('span', { class: 'note-date', text: n.date + (n.author ? ' by ' + n.author : '') }), h('p', { text: n.text })); }))) : null; var events = fullPlan ? fullPlan.events : null; var tl = events ? colTimeline(events, plan.column, plan.enteredColumnAt, plan.limitMs, PLAN_COL_LABELS) : null; fill(body, [ h('div', { class: 'dlg-head' }, h('div', null, h('span', { class: 'chip st-' + plan.column.replace(/\s/g, '-'), text: PLAN_COL_LABELS[plan.column] || plan.column }), h('h2', { id: 'plan-title', style: 'margin-top:10px', text: plan.title })), h('button', { type: 'button', class: 'icon-btn', 'aria-label': 'Close', onclick: function() { dlg.close(); } }, icon('close'))), h('dl', { class: 'meta' }, h('dt', { text: 'Project' }), h('dd', { text: projectName(plan.projectId) }), h('dt', { text: 'Priority' }), h('dd', { text: plan.priority != null ? 'P' + plan.priority : 'Not set' }), h('dt', { text: 'Time in column' }), h('dd', { text: fmtAge(plan.ageMs) + (plan.stalled ? ' (stalled)' : '') }), plan.linkedWorkCount ? h('dt', { text: 'Linked work' }) : null, plan.linkedWorkCount ? h('dd', { text: plan.linkedWorkCount + ' items' }) : null), bodyEl, notes, tl ? h('section', { class: 'stack' }, h('h3', { text: 'Status history' }), tl) : null ]); }; // Show skeleton, then lazy-load full plan detail fill(body, [ h('div', { class: 'dlg-head' }, h('div', null, h('span', { class: 'chip st-' + plan.column.replace(/\s/g, '-'), text: PLAN_COL_LABELS[plan.column] || plan.column }), h('h2', { id: 'plan-title', style: 'margin-top:10px', text: plan.title })), h('button', { type: 'button', class: 'icon-btn', 'aria-label': 'Close', onclick: function() { dlg.close(); } }, icon('close'))), h('dl', { class: 'meta' }, h('dt', { text: 'Project' }), h('dd', { text: projectName(plan.projectId) }), h('dt', { text: 'Priority' }), h('dd', { text: plan.priority != null ? 'P' + plan.priority : 'Not set' }), h('dt', { text: 'Time in column' }), h('dd', { text: fmtAge(plan.ageMs) + (plan.stalled ? ' (stalled)' : '') })), h('div', { class: 'skel', style: 'height:80px;margin-top:12px' }) ]); dlg.showModal(); if (PLAN_DETAIL_CACHE[c.id]) { renderPlanDetail(PLAN_DETAIL_CACHE[c.id]); return; } if (navigator.onLine === false) { renderPlanDetail(null); return; } getJson('/api/plans/get?id=' + encodeURIComponent(c.id)).then(function(res) { if (res && res.plan) { PLAN_DETAIL_CACHE[c.id] = { body: res.plan.body, events: res.plan.events, progressNotes: res.plan.progressNotes }; renderPlanDetail(PLAN_DETAIL_CACHE[c.id]); } else { renderPlanDetail(null); } }).catch(function() { renderPlanDetail(null); }); }); } var DND = { id: null, kind: null, fromCol: null }; var REDUCED_MOTION = window.matchMedia ? matchMedia('(prefers-reduced-motion: reduce)').matches : false; function moveToMenu(cardId, kind, fromCol, colLabels, validMoves) { var wrap = h('div', { class: 'bcard-wrap', style: 'position:relative' }); var btn = h('button', { type: 'button', class: 'move-btn', 'aria-label': 'Move to', title: 'Move to', onclick: function(e) { e.stopPropagation(); togglePop(); } }, icon('move')); var pop = h('div', { class: 'move-pop', hidden: true }); var allowed = validMoves[fromCol] || []; for (var mi = 0; mi < allowed.length; mi++) { (function(target) { pop.append(h('button', { type: 'button', text: colLabels[target] || target, onclick: function(e) { e.stopPropagation(); pop.hidden = true; doMove(kind, cardId, target, fromCol); }})); })(allowed[mi]); } if (!allowed.length) pop.append(h('button', { type: 'button', text: 'No moves available', disabled: true })); function togglePop() { pop.hidden = !pop.hidden; } function closePop(e) { if (!wrap.contains(e.target)) pop.hidden = true; } document.addEventListener('click', closePop); wrap.append(btn, pop); return wrap; } async function doMove(kind, id, to, from) { try { var data = await postMove(kind, id, to, 'moved via board'); if (data.moved === false) { toast('Cannot move: ' + (data.reason || 'invalid')); return; } invalidateData(); toast('Moved to ' + (BOARD_COL_LABELS[to] || PLAN_COL_LABELS[to] || to)); if (RENDER) RENDER(); } catch (e) { toast('Move failed: ' + (e.message || 'unknown error')); if (RENDER) RENDER(); } } function buildPipelineStrip(stripEl, columns, colOrder, colLabels, scrollEl, projectFilter, stalledOnly) { if (!stripEl) return; fill(stripEl, colOrder.map(function(col) { var cards = columns[col] || []; if (projectFilter) cards = cards.filter(function(c) { return c.projectId === projectFilter; }); if (stalledOnly) cards = cards.filter(function(c) { return c.stalled; }); var count = cards.length; var stalled = cards.filter(function(c) { return c.stalled; }).length; var cls = 'pipe-seg' + (count ? ' has-cards' : '') + (stalled ? ' has-stalled' : ''); return h('button', { type: 'button', class: cls, 'data-col': col, 'aria-pressed': 'false', onclick: function() { var target = scrollEl.querySelector('[data-col="' + col + '"]'); if (target) target.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' }); $$('.pipe-seg', stripEl).forEach(function(s) { s.setAttribute('aria-pressed', String(s.dataset.col === col)); }); } }, h('span', { class: 'pipe-label', text: colLabels[col] || col }), h('span', { class: 'pipe-count', text: String(count) }), stalled ? h('span', { class: 'pipe-stall' }, icon('alert'), String(stalled)) : null ); })); } function buildBoard(container, columns, colOrder, colLabels, cardFn, stalledOnly, projectFilter, kind) { var now = Date.now(); var validMoves = kind === 'plan' ? PLAN_VALID_MOVES : WORK_VALID_MOVES; var colEls = []; for (var ci = 0; ci < colOrder.length; ci++) { (function(col) { var cards = columns[col] || []; if (projectFilter) cards = cards.filter(function(c) { return c.projectId === projectFilter; }); if (stalledOnly) cards = cards.filter(function(c) { return c.stalled; }); cards.forEach(function(c) { c.ageMs = Math.max(0, now - Date.parse(c.enteredColumnAt)); }); var stalledCount = cards.filter(function(c) { return c.stalled; }).length; var isEmpty = cards.length === 0; var cardEls = cards.map(function(c) { var el = cardFn(c); var wrap = h('div', { class: 'bcard-wrap', style: 'position:relative' }); var menu = moveToMenu(c.id, kind || 'work', c.column, colLabels, validMoves); wrap.append(el); var menuBtn = menu.querySelector('.move-btn'); var menuPop = menu.querySelector('.move-pop'); if (menuBtn) wrap.append(menuBtn); if (menuPop) wrap.append(menuPop); el.addEventListener('dragstart', function(e) { DND.id = c.id; DND.kind = kind || 'work'; DND.fromCol = c.column; el.classList.add('dragging'); e.dataTransfer.effectAllowed = 'move'; try { e.dataTransfer.setData('text/plain', c.id); } catch(ex) {} }); el.addEventListener('dragend', function() { el.classList.remove('dragging'); DND.id = null; DND.kind = null; DND.fromCol = null; $$('.bcol', container).forEach(function(ce) { ce.classList.remove('drop-ok', 'drop-no'); }); }); return wrap; }); var colEl = h('div', { class: 'bcol' + (isEmpty ? ' bcol-empty-col' : ''), 'data-col': col }, h('div', { class: 'bcol-head' }, h('span', null, colLabels[col] || col, ' ', h('span', { class: 'cnt', text: '(' + cards.length + ')' })), stalledCount ? h('span', { class: 'stall-cnt', text: stalledCount + ' stalled' }) : null), cardEls.length ? cardEls : h('div', { class: 'bcol-empty', text: 'No items' }) ); colEl.addEventListener('dragover', function(e) { e.preventDefault(); if (!DND.id) return; var ok = canMove(DND.fromCol, col, DND.kind); e.dataTransfer.dropEffect = ok ? 'move' : 'none'; if (!REDUCED_MOTION) { colEl.classList.toggle('drop-ok', ok); colEl.classList.toggle('drop-no', !ok); } }); colEl.addEventListener('dragleave', function() { colEl.classList.remove('drop-ok', 'drop-no'); }); colEl.addEventListener('drop', function(e) { e.preventDefault(); colEl.classList.remove('drop-ok', 'drop-no'); if (!DND.id || DND.fromCol === col) return; if (!canMove(DND.fromCol, col, DND.kind)) { toast('Cannot move from ' + (colLabels[DND.fromCol] || DND.fromCol) + ' to ' + (colLabels[col] || col) + '; that transition is managed by the sweep.'); return; } doMove(DND.kind || 'work', DND.id, col, DND.fromCol); }); colEls.push(colEl); })(colOrder[ci]); } fill(container, colEls); } function setupMobileTabs(tabsEl, scrollEl, colOrder, colLabels, columns, projectFilter, stalledOnly) { if (!tabsEl || !scrollEl) return; tabsEl.hidden = false; var firstStalled = -1, firstNonEmpty = -1; for (var ti = 0; ti < colOrder.length; ti++) { var cc = columns[colOrder[ti]] || []; if (projectFilter) cc = cc.filter(function(c) { return c.projectId === projectFilter; }); if (stalledOnly) cc = cc.filter(function(c) { return c.stalled; }); if (firstNonEmpty < 0 && cc.length) firstNonEmpty = ti; if (firstStalled < 0 && cc.some(function(c) { return c.stalled; })) firstStalled = ti; } var defaultIdx = firstStalled >= 0 ? firstStalled : (firstNonEmpty >= 0 ? firstNonEmpty : 0); fill(tabsEl, colOrder.map(function(col, i) { var cc2 = columns[col] || []; if (projectFilter) cc2 = cc2.filter(function(c) { return c.projectId === projectFilter; }); if (stalledOnly) cc2 = cc2.filter(function(c) { return c.stalled; }); var count = cc2.length; var stalled = cc2.filter(function(c) { return c.stalled; }).length; var label = (colLabels[col] || col) + ' (' + count + ')'; if (stalled) label += ' ' + stalled + ' stalled'; return h('button', { type: 'button', 'data-col': col, 'aria-pressed': String(i === defaultIdx), text: label, onclick: function() { $$('button', tabsEl).forEach(function(b) { b.setAttribute('aria-pressed', String(b.dataset.col === col)); }); var target = scrollEl.querySelector('[data-col="' + col + '"]'); if (target) target.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' }); } }); })); if (defaultIdx > 0) { var defaultCol = colOrder[defaultIdx]; var target = scrollEl.querySelector('[data-col="' + defaultCol + '"]'); // Scroll only the board horizontally on load; never move the page down past the header and pipeline strip. if (target) scrollEl.scrollLeft += target.getBoundingClientRect().left - scrollEl.getBoundingClientRect().left; } } var BOARD_AGE_TIMER = null; function startAgeTicker(container) { if (BOARD_AGE_TIMER) clearTimeout(BOARD_AGE_TIMER); function tick() { var now = Date.now(); $$('.bcard-age', container).forEach(function(el) { var card = el.closest('.bcard'); if (!card) return; var entered = card.dataset.entered; if (entered) { var ms = Math.max(0, now - Number(entered)); var col = card.dataset.column || ''; var limit = Number(card.dataset.limit) || 0; var stalled = limit > 0 && ms >= limit; var warn = limit > 0 && ms >= limit * 0.75 && !stalled; var label = (BOARD_COL_LABELS[col] || PLAN_COL_LABELS[col] || col); el.textContent = ''; el.className = 'bcard-age' + (stalled ? ' over' : warn ? ' warn' : ''); el.append(icon('clock'), stalled ? fmtAge(ms) + ' in ' + label + ' (stalled)' : fmtAge(ms) + ' in ' + label); } }); BOARD_AGE_TIMER = setTimeout(tick, 60000); } BOARD_AGE_TIMER = setTimeout(tick, 60000); } function buildCategoryChips(container, categoryCounts, activeCategories, onChange) { if (!container) return; var chips = []; var seen = {}; var allCats = ALL_CATEGORIES.slice(); for (var ck in categoryCounts) if (categoryCounts[ck] > 0 && allCats.indexOf(ck) < 0) allCats.push(ck); for (var ci = 0; ci < allCats.length; ci++) { (function(cat) { var count = categoryCounts[cat] || 0; if (count === 0 && activeCategories.indexOf(cat) < 0) return; var active = activeCategories.length === 0 || activeCategories.indexOf(cat) >= 0; var btn = h('button', { type: 'button', class: 'cat-filter' + (active ? ' active' : ''), 'data-category': cat, 'aria-pressed': String(active), style: active ? '--cat-c:' + (CATEGORY_COLORS[cat] || '#475569') : '', onclick: function() { var idx = activeCategories.indexOf(cat); if (idx >= 0) activeCategories.splice(idx, 1); else activeCategories.push(cat); var p = new URLSearchParams(location.search); if (activeCategories.length) p.set('category', activeCategories.join(',')); else p.delete('category'); history.replaceState(null, '', location.pathname + (p.toString() ? '?' + p : '')); onChange(); } }, h('span', { text: (CATEGORY_LABELS[cat] || cat) + ' (' + count + ')' })); chips.push(btn); })(allCats[ci]); } fill(container, chips); } function filterByCategory(columns, activeCategories) { if (!activeCategories.length) return columns; var filtered = {}; for (var col in columns) { filtered[col] = (columns[col] || []).filter(function(c) { return activeCategories.indexOf(c.category) >= 0; }); } return filtered; } async function renderBoard() { var board = $('#board'), sel = $('#board-project'), stalledCb = $('#board-stalled-only'), droppedCb = $('#board-show-dropped'); var params = new URLSearchParams(location.search); var catParam = params.get('category') || ''; var activeCategories = catParam ? catParam.split(',').filter(function(c) { return ALL_CATEGORIES.indexOf(c) >= 0; }) : []; var st = { project: params.get('project') || '', stalledOnly: params.get('stalledOnly') === '1', showDropped: false }; if (stalledCb && st.stalledOnly) stalledCb.checked = true; var drawBoard = function() {}; var draw = function() { var cols = st.showDropped ? BOARD_COLS : BOARD_COLS.filter(function(c) { return c !== 'dropped'; }); drawBoard(cols); }; if (sel) sel.addEventListener('change', function() { st.project = sel.value; draw(); }); if (stalledCb) stalledCb.addEventListener('change', function() { st.stalledOnly = stalledCb.checked; draw(); }); if (droppedCb) droppedCb.addEventListener('change', function() { st.showDropped = droppedCb.checked; draw(); }); try { await withData(function(d) { if (!d.board) return; fill(sel, [h('option', { value: '', text: 'All projects' })].concat(PROJECTS.map(function(p) { return h('option', { value: p.id, text: p.displayName }); }))); var unified = d.board.unified || { columns: d.board.work.columns, categoryCounts: {} }; buildCategoryChips($('#board-category-chips'), unified.categoryCounts, activeCategories, draw); drawBoard = function(cols) { var cardFnWrap = function(c) { var el = bcard(c); el.dataset.entered = String(Date.parse(c.enteredColumnAt)); el.dataset.column = c.column; el.dataset.limit = String(c.limitMs); return el; }; var activeCols = cols || BOARD_COLS.filter(function(c2) { return c2 !== 'dropped'; }); var filteredColumns = filterByCategory(unified.columns, activeCategories); buildPipelineStrip($('#board-pipe-strip'), filteredColumns, activeCols, BOARD_COL_LABELS, $('#board-scroll'), st.project, st.stalledOnly); buildBoard(board, filteredColumns, activeCols, BOARD_COL_LABELS, cardFnWrap, st.stalledOnly, st.project, 'work'); setupMobileTabs($('#board-mobile-tabs'), $('#board-scroll'), activeCols, BOARD_COL_LABELS, filteredColumns, st.project, st.stalledOnly); }; draw(); startAgeTicker(board); footer(); }); } catch (e) { fill(board, errorBox(e.message)); } } async function renderPlans() { var board = $('#plans-board'), sel = $('#plans-project'), archivedCb = $('#plans-show-archived'); var st = { project: '', showArchived: false }; var drawBoard = function() {}; var draw = function() { drawBoard(); }; if (sel) sel.addEventListener('change', function() { st.project = sel.value; draw(); }); if (archivedCb) archivedCb.addEventListener('change', function() { st.showArchived = archivedCb.checked; draw(); }); var createBtn = $('#create-plan-btn'); if (createBtn) createBtn.addEventListener('click', function() { var dlg = $('#plan-edit-dialog'); if (!dlg) return; var form = $('#plan-edit-form'); if (form) form.reset(); $('#plan-edit-title').textContent = 'New plan'; $('#plan-edit-error').hidden = true; form._planId = null; dlg.showModal(); }); var planForm = $('#plan-edit-form'); if (planForm) planForm.addEventListener('submit', async function(ev) { ev.preventDefault(); var f = planForm.elements; var title = f.title.value.trim(); if (!title) { var err = $('#plan-edit-error'); err.textContent = 'Title is required'; err.hidden = false; return; } var body = { title: title, body: f.body.value, status: f.status.value, priority: f.priority.value === '' ? null : Number(f.priority.value) }; if (planForm._planId) body.id = planForm._planId; var btn = planForm.querySelector('[type=submit]'); btn.disabled = true; btn.textContent = 'Saving...'; try { var r = await fetch(url('/api/plans/upsert'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); var data = await r.json(); if (!r.ok || !data.plan) throw new Error(data.error || 'Save failed'); $('#plan-edit-dialog').close(); invalidateData(); toast(planForm._planId ? 'Plan updated.' : 'Plan created.'); if (RENDER) RENDER(); } catch (e) { var err2 = $('#plan-edit-error'); err2.textContent = e.message; err2.hidden = false; } btn.disabled = false; btn.textContent = 'Save'; }); try { await withData(function(d) { if (!d.board || !d.board.plans) return; fill(sel, [h('option', { value: '', text: 'All projects' })].concat(PROJECTS.map(function(p) { return h('option', { value: p.id, text: p.displayName }); }))); drawBoard = function() { var cardFnWrap = function(c) { var el = planCard(c); el.dataset.entered = String(Date.parse(c.enteredColumnAt)); el.dataset.column = c.column; el.dataset.limit = String(c.limitMs); return el; }; var filteredCols; if (!st.showArchived) { filteredCols = {}; for (var k2 in d.board.plans.columns) filteredCols[k2] = (d.board.plans.columns[k2] || []).filter(function(c) { return !c.archived; }); } else { filteredCols = d.board.plans.columns; } buildBoard(board, filteredCols, PLAN_COLS, PLAN_COL_LABELS, cardFnWrap, false, st.project, 'plan'); setupMobileTabs($('#plans-mobile-tabs'), $('#plans-scroll'), PLAN_COLS, PLAN_COL_LABELS, filteredCols, st.project, false); }; draw(); startAgeTicker(board); footer(); }); } catch (e) { fill(board, errorBox(e.message)); } } // Inline SVG sparkline (no external libs) function sparkline(data, opts) { var w = opts && opts.width || 120, ht = opts && opts.height || 28; var max = 0; for (var si = 0; si < data.length; si++) if (data[si].v > max) max = data[si].v; if (!max) max = 1; var barW = Math.max(2, Math.floor((w - data.length + 1) / data.length)); var bars = data.map(function(d) { var bh = Math.max(1, Math.round((d.v / max) * (ht - 2))); var cls = d.v === 0 ? 'zero' : (d.err ? 'err' : ''); return ''; }).join(''); var label = data.map(function(d) { return d.label + ': ' + d.v; }).join(', '); var el = h('span', { class: 'spark-inline', role: 'img', 'aria-label': label, style: 'height:' + ht + 'px' }); el.innerHTML = bars; return el; } function pdEmpty(msg, iconName) { return h('div', { class: 'pd-empty' }, icon(iconName || 'inbox'), h('p', { text: msg })); } function pdSection(title, content) { return h('section', { class: 'card pd-section' }, h('h2', { text: title }), content); } var SOURCE_LABELS = { runId: 'Active session', link: 'Linked session', postMerge: 'Post-merge fix' }; function renderAgentsSection(d) { var agents = d.agents; if (agents.error) return pdSection('Agents', pdEmpty(agents.error, 'alert')); var parts = []; if (agents.sessions.length) { var rows = agents.sessions.slice(0, 10).map(function(s) { var live = null; if (agents.devinLive && !agents.devinLive.error) { live = agents.devinLive.find(function(l) { return l.runId === s.runId; }); } var stateText = live ? live.state : s.state; var stateCls = stateText === 'running' ? 'on' : stateText === 'succeeded' ? 'on' : stateText === 'failed' ? 'warn' : ''; var links = []; if (s.url) links.push(h('a', { href: s.url, target: '_blank', rel: 'noreferrer', class: 'link small', text: 'Session' })); if (s.prUrl) links.push(h('a', { href: s.prUrl, target: '_blank', rel: 'noreferrer', class: 'link small', text: 'PR #' + s.prNumber })); links.push(h('a', { href: url('/board?project=' + encodeURIComponent(d.project.id)), class: 'link small', text: 'Board' })); return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title', text: s.title }), h('div', { class: 'pd-row-sub' }, h('span', { class: 'chip ' + stateCls, text: stateText }), ' ', (SOURCE_LABELS[s.source] || s.source), ' ', h('span', { class: 'muted', text: (BOARD_COL_LABELS[s.column] || s.column) })), h('div', { class: 'pd-row-sub', style: 'display:flex;gap:10px' }, links)), h('div', { class: 'pd-row-side' }, h('span', { class: 'muted small', text: age(s.startedAt) }))); }); parts.push(h('div', null, rows)); } else { parts.push(pdEmpty('No agent sessions found for this project.', 'inbox')); } if (agents.devinLive && agents.devinLive.error) { parts.push(h('p', { class: 'muted small', text: 'Live Devin status: ' + agents.devinLive.error })); } parts.push(h('p', { class: 'muted small', text: 'Cost data not available from the Devin API.' })); parts.push(h('p', { class: 'muted small', text: agents.t3Note })); return pdSection('Agents', h('div', { class: 'stack' }, parts)); } function renderRunsSection(d) { var runs = d.runs; if (runs.error) return pdSection('Automated runs', pdEmpty(runs.error, 'alert')); var parts = []; var kpi = h('div', { class: 'pd-kpi' }, h('div', { class: 'pd-kpi-box' }, h('b', { text: String(runs.total24h) }), h('span', { text: 'automation runs (24h)' }), h('small', { text: runs.errors24h + ' failed, ' + (runs.delivered24h || 0) + ' webhook deliveries' })), h('div', { class: 'pd-kpi-box' }, h('b', { text: String(runs.total7d) }), h('span', { text: 'automation runs (7d)' }), h('small', { text: runs.errors7d + ' failed' })), h('div', { class: 'pd-kpi-box' }, h('b', null, sparkline(runs.byDay.map(function(dd) { return { v: dd.total, err: dd.errors > 0, label: dd.date + ': ' + dd.total + ' runs, ' + dd.deliveries + ' deliveries' }; }), { width: 80, height: 24 })), h('span', { text: 'last 7 days' }))); parts.push(kpi); if (runs.groups.length) { var rows = runs.groups.map(function(g) { var attrLabel = g.attribution === 'repo-specific' ? (g.repoRef || 'repo') : 'factory-wide'; var skippedNote = g.skipped ? ', ' + g.skipped + ' skipped' : ''; return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title' }, g.name, ' ', h('span', { class: 'chip small', text: g.surface })), h('div', { class: 'pd-row-sub' }, g.total + ' runs, ' + g.errors + ' failed' + skippedNote + ' ', h('span', { class: 'chip ' + (g.attribution === 'repo-specific' ? 'on' : ''), text: attrLabel })), g.lastError ? h('div', { class: 'pd-row-sub err', text: g.lastError }) : null), h('div', { class: 'pd-row-side' }, h('span', { class: 'muted small', text: g.lastAt ? age(g.lastAt) : 'never' }))); }); parts.push(h('div', null, h('h3', { text: 'By type' }), rows)); } else { parts.push(pdEmpty('No recent automation runs found. Page loads and export handler runs are excluded.', 'inbox')); } if (runs.deploys && runs.deploys.length) { parts.push(h('div', null, h('h3', { text: 'Recent publishes' }), runs.deploys.map(function(dep) { return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title', text: 'Publish' + (dep.commit ? ' ' + dep.commit : '') }), h('div', { class: 'pd-row-sub', text: dep.status })), h('div', { class: 'pd-row-side' }, h('span', { class: 'muted small', text: dep.at ? age(dep.at) : '' }))); }))); } parts.push(h('p', { class: 'muted small', text: 'Excludes page loads and paired export handler runs. Webhook deliveries are counted once per incoming event.' })); return pdSection('Automated runs', h('div', { class: 'stack' }, parts)); } function renderFlowSection(d) { var f = d.flow; var parts = []; // KPIs var ct = f.cycleTime; var ctText, ctCaption; if (ct.sample === 0) { ctText = '--'; ctCaption = 'No completed items'; } else if (ct.sample < 3) { ctText = fmtAge(ct.medianMs); ctCaption = 'Small sample (n=' + ct.sample + ')'; } else { ctText = fmtAge(ct.medianMs); ctCaption = 'p90: ' + fmtAge(ct.p90Ms) + ', n=' + ct.sample; } var shipped14 = 0, dropped14 = 0, activity14 = 0; for (var ti = 0; ti < f.throughput.length; ti++) { shipped14 += f.throughput[ti].shipped; dropped14 += f.throughput[ti].dropped; activity14 += f.throughput[ti].shipped + f.throughput[ti].dropped + f.throughput[ti].advanced; } var kpi = h('div', { class: 'pd-kpi' }, h('div', { class: 'pd-kpi-box' }, h('b', { text: String(shipped14) }), h('span', { text: 'shipped (14d)' }), h('small', { text: dropped14 + ' dropped' })), h('div', { class: 'pd-kpi-box' }, h('b', { text: ctText }), h('span', { text: 'cycle time (median)' }), h('small', { text: ctCaption })), h('div', { class: 'pd-kpi-box' }, h('b', { text: String(activity14) }), h('span', { text: 'events (14d)' }), h('small', null, sparkline(f.throughput.map(function(dd) { return { v: dd.shipped + dd.dropped + dd.advanced, label: dd.date }; }), { width: 80, height: 20 })))); parts.push(kpi); // Column distribution if (f.byColumn.length) { var total = 0; for (var bi = 0; bi < f.byColumn.length; bi++) total += f.byColumn[bi].count; if (total > 0) { var colBars = f.byColumn.filter(function(c) { return c.count > 0; }).map(function(c) { return h('div', { class: 'pd-col-bar' }, h('span', { text: c.label }), h('div', { class: 'bar' }, h('i', { style: 'width:' + (c.count / total * 100) + '%' })), h('b', { text: String(c.count) })); }); parts.push(h('div', null, h('h3', { text: 'Items by column' }), h('div', { class: 'pd-col-bars', style: 'margin-top:8px' }, colBars))); } } // Stalls if (f.stalls.length) { parts.push(h('div', null, h('h3', null, f.stalls.length + ' stalled'), h('div', null, f.stalls.slice(0, 5).map(function(s) { return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title', text: s.title }), h('div', { class: 'pd-row-sub', text: (BOARD_COL_LABELS[s.column] || s.column) + ' for ' + fmtAge(s.ageMs) })), h('span', { class: 'stalled-age', text: fmtAge(s.stalledBy) + ' over' })); })))); } // Column time medians if (f.columnTimes.length) { var ctRows = f.columnTimes.filter(function(c) { return c.sample >= 3; }); if (ctRows.length) { parts.push(h('div', null, h('h3', { text: 'Median time per column' }), h('div', { class: 'pd-col-bars', style: 'margin-top:8px' }, ctRows.map(function(c) { var maxCt = 0; for (var ci2 = 0; ci2 < ctRows.length; ci2++) if (ctRows[ci2].medianMs > maxCt) maxCt = ctRows[ci2].medianMs; return h('div', { class: 'pd-col-bar' }, h('span', { text: c.label }), h('div', { class: 'bar' }, h('i', { style: 'width:' + (maxCt ? c.medianMs / maxCt * 100 : 0) + '%' })), h('b', { text: fmtAge(c.medianMs) + ' (n=' + c.sample + ')' })); })))); } } // Linked plans - grouped by status, top 5 by priority if (f.linkedPlans.length) { var plansByStatus = {}; for (var pi2 = 0; pi2 < f.linkedPlans.length; pi2++) { var pp = f.linkedPlans[pi2]; if (!plansByStatus[pp.status]) plansByStatus[pp.status] = []; plansByStatus[pp.status].push(pp); } var statusOrder = ['exploring', 'proposed', 'decided', 'in-progress', 'shipped']; var statusCounts = statusOrder.filter(function(ss) { return plansByStatus[ss] && plansByStatus[ss].length; }).map(function(ss) { return h('span', { class: 'chip st-' + ss.replace(/\s/g, '-'), text: (PLAN_COL_LABELS[ss] || ss) + ' (' + plansByStatus[ss].length + ')' }); }); var sorted = f.linkedPlans.slice().sort(function(a, b) { return (a.priority == null ? 9 : a.priority) - (b.priority == null ? 9 : b.priority); }); var shown = sorted.slice(0, 5); var rest = sorted.slice(5); var planRows = function(list) { return list.map(function(lp) { return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title', text: lp.title }), lp.priority != null ? h('div', { class: 'pd-row-sub prio', text: 'P' + lp.priority }) : null), h('span', { class: 'chip st-' + lp.status.replace(/\s/g, '-'), text: PLAN_COL_LABELS[lp.status] || lp.status })); }); }; var planWrap = h('div', null, planRows(shown)); var restWrap = null; if (rest.length) { restWrap = h('div', { hidden: true }); fill(restWrap, planRows(rest)); var toggleBtn = h('button', { type: 'button', class: 'link small', style: 'margin-top:6px', text: 'Show all ' + f.linkedPlans.length, onclick: function() { restWrap.hidden = !restWrap.hidden; toggleBtn.textContent = restWrap.hidden ? 'Show all ' + f.linkedPlans.length : 'Show fewer'; } }); } parts.push(h('div', null, h('div', { style: 'display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px' }, h('h3', { text: plural(f.linkedPlans.length, 'plan') }), statusCounts, h('a', { class: 'link small', href: url('/plans'), text: 'All plans' })), planWrap, restWrap, toggleBtn || null)); } // Recent activity if (f.recentActivity.length) { parts.push(h('div', null, h('h3', { text: 'Recent activity' }), h('ul', { class: 'pd-activity' }, f.recentActivity.slice(0, 15).map(function(a) { return h('li', { class: 'pd-act' }, h('div', null, h('strong', { text: a.kind }), ' ', a.title), h('div', { class: 'pd-act-time' }, a.detail + ' / ' + fmtFull(a.at))); })))); } return pdSection('Flow metrics', h('div', { class: 'stack' }, parts.length ? parts : [pdEmpty('No work items in this project yet.', 'inbox')])); } function renderPrsSection(d) { var prs = d.prs; var parts = []; if (prs.open.length) { parts.push(h('div', null, h('h3', { text: plural(prs.open.length, 'open PR') }), h('div', null, prs.open.map(function(p) { return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title' }, h('a', { href: p.url, target: '_blank', rel: 'noreferrer', text: p.title + ' #' + p.number })), h('div', { class: 'pd-row-sub' }, 'Checks: ' + p.checks + ' / Review: ' + p.reviewState + (p.ready ? ' / Ready' : ''))), h('span', { class: 'chip sub-' + (p.checks === 'success' && p.reviewState === 'approved' ? 'ready_to_merge' : p.checks === 'failure' ? 'needs_attention' : 'waiting'), text: p.checks === 'success' && p.reviewState === 'approved' ? 'Ready' : p.checks === 'failure' ? 'CI failing' : 'In progress' })); })))); } else { parts.push(pdEmpty('No open PRs.', 'branch')); } // Main CI if (prs.mainCi) { if (prs.mainCi.error) { parts.push(h('p', { class: 'muted small', text: prs.mainCi.error })); } else { var ciCls = prs.mainCi.status === 'success' ? 'on' : prs.mainCi.status === 'failure' ? 'warn' : ''; parts.push(h('div', { style: 'display:flex;align-items:center;gap:8px' }, h('span', { class: 'chip ' + ciCls, text: 'Main: ' + prs.mainCi.status }), h('span', { class: 'muted small', text: prs.mainCi.repo + ' / checked ' + age(prs.mainCi.checkedAt) }))); } } // Post-merge watches if (prs.postMergeWatches.length) { parts.push(h('div', null, h('h3', { text: 'Watching main after merge' }), h('div', null, prs.postMergeWatches.map(function(w) { return h('div', { class: 'pd-row' }, h('div', { class: 'pd-row-main' }, h('div', { class: 'pd-row-title', text: w.title }), h('div', { class: 'pd-row-sub', text: w.phase + ' since ' + fmtFull(w.startedAt) }))); })))); } return pdSection('PRs and CI', h('div', { class: 'stack' }, parts)); } function renderCostSection(projectId) { var section = h('section', { class: 'card stack', 'aria-label': 'Cost signals' }, h('h2', { text: 'Cost signals' }), h('p', { class: 'muted small', text: 'Loading cost data...' })); getJson('/api/projects/' + encodeURIComponent(projectId) + '/costs').then(function(c) { var items = []; items.push(h('li', null, h('div', null, h('b', { text: 'Agent runs started' }), h('span', { class: 'd', text: 'Total runs initiated for this project' })), h('span', { class: 'chip', text: String(c.runsStarted) }))); items.push(h('li', null, h('div', null, h('b', { text: 'Runs completed' }), h('span', { class: 'd', text: 'Runs that finished successfully' })), h('span', { class: 'chip on', text: String(c.runsCompleted) }))); items.push(h('li', null, h('div', null, h('b', { text: 'Runs failed' }), h('span', { class: 'd', text: 'Runs that failed or were cancelled' })), h('span', { class: 'chip ' + (c.runsFailed ? 'warn' : ''), text: String(c.runsFailed) }))); if (c.avgRunDurationMs != null) { var hrs = Math.floor(c.avgRunDurationMs / 3600000); var mins = Math.floor((c.avgRunDurationMs % 3600000) / 60000); items.push(h('li', null, h('div', null, h('b', { text: 'Average run duration' }), h('span', { class: 'd', text: 'Time from start to completion' })), h('span', { class: 'chip', text: (hrs ? hrs + 'h ' : '') + mins + 'm' }))); } var totalHrs = Math.floor(c.totalRunDurationMs / 3600000); var totalMins = Math.floor((c.totalRunDurationMs % 3600000) / 60000); if (c.totalRunDurationMs > 0) { items.push(h('li', null, h('div', null, h('b', { text: 'Total run time' }), h('span', { class: 'd', text: 'Cumulative agent run time' })), h('span', { class: 'chip', text: (totalHrs ? totalHrs + 'h ' : '') + totalMins + 'm' }))); } items.push(h('li', null, h('div', null, h('b', { text: 'Items shipped' }), h('span', { class: 'd', text: 'Work items completed and shipped' })), h('span', { class: 'chip on', text: String(c.itemsShipped) }))); items.push(h('li', null, h('div', null, h('b', { text: 'Items dropped' }), h('span', { class: 'd', text: 'Work items closed without shipping' })), h('span', { class: 'chip', text: String(c.itemsDropped) }))); if (!c.acuAvailable) { items.push(h('li', null, h('div', null, h('b', { text: 'Devin ACUs' }), h('span', { class: 'd', text: c.costNote })), h('span', { class: 'chip', text: 'Not available' }))); } var content = [h('h2', { text: 'Cost signals' }), h('ul', { class: 'kv' }, items)]; if (c.period.from) { content.push(h('p', { class: 'muted small', text: 'Data from ' + fmtDate(c.period.from) + ' to now' })); } else { content.push(h('p', { class: 'muted small', text: 'No agent runs recorded for this project yet.' })); } fill(section, content); }).catch(function(e) { fill(section, [h('h2', { text: 'Cost signals' }), h('p', { class: 'muted', text: 'Could not load cost data.' })]); }); return section; } async function renderProjectDetail() { var pathParts = location.pathname.replace(BP, '').split('/').filter(Boolean); var projectId = decodeURIComponent(pathParts[1] || ''); if (!projectId) return; var grid = $('#pd-grid'); try { var d = await getJson('/api/projects/' + encodeURIComponent(projectId) + '/overview'); if (d.error) { fill(grid, errorBox(d.error)); return; } // Header: set text and remove skeleton classes var p = d.project; var pdTitle = $('#pd-title'); pdTitle.textContent = p.displayName || p.id; pdTitle.className = ''; var pdCrumb = $('#pd-crumb'); pdCrumb.textContent = p.displayName || p.id; pdCrumb.className = ''; var pdSub = $('#pd-sub'); pdSub.textContent = p.repos.map(function(r) { return r.repoRef; }).join(', ') || 'No repositories'; pdSub.className = 'muted'; var badges = []; badges.push(h('span', { class: 'chip ' + (p.enabled ? 'on' : 'off'), text: p.enabled ? 'Enabled' : 'Disabled' })); badges.push(h('span', { class: 'chip ' + (d.inPilotScope ? 'on' : ''), text: d.inPilotScope ? 'In pilot scope' : 'Outside pilot scope' })); fill($('#pd-badges'), badges); fill($('#pd-actions'), [ h('a', { class: 'btn', href: url('/board?project=' + encodeURIComponent(projectId)), text: 'Board' }), h('a', { class: 'btn', href: url('/work?project=' + encodeURIComponent(projectId)), text: 'Work queue' }) ]); // Sections fill(grid, [ renderAgentsSection(d), renderRunsSection(d), renderFlowSection(d), renderPrsSection(d), renderCostSection(projectId) ]); footer(); } catch (e) { fill(grid, errorBox(e.message)); } } // Notifications view var NOTIF_CATEGORIES = ['stall', 'needs-kent', 'state-change', 'pr-update', 'error', 'health', 'agent', 'merge']; var SEVERITY_ICONS = { error: 'alert', warning: 'alert', info: 'inbox' }; var SEVERITY_CLS = { error: 'chip lvl-bad', warning: 'chip lvl-warn', info: 'chip lvl-ok' }; function notifRow(n) { return h('button', { type: 'button', class: 'row' + (n.status === 'unread' ? ' flash-row' : ''), 'data-id': n.id, onclick: function() { if (n.status === 'unread') { fetch(url('/api/notifications/mark-read'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ ids: [n.id] }) }).then(function() { updateNotifBadge(); }); n.status = 'read'; } } }, h('span', { class: 'src', style: 'background:var(--panel2)' }, icon(SEVERITY_ICONS[n.severity] || 'inbox')), h('span', null, h('span', { class: 'row-title', text: n.title }), h('span', { class: 'row-meta' }, h('span', { class: SEVERITY_CLS[n.severity] || 'chip', text: n.severity }), h('span', { text: n.category }), h('span', { text: projectName(n.projectId) }), h('span', { text: age(n.createdAt) }))), h('span', { class: 'chip ' + (n.status === 'unread' ? 'warn' : ''), text: n.status })); } function updateNotifBadge() { withData(function(d) { var badge = document.querySelector('.nav a[href*="notifications"] .notif-badge'); var count = d.unreadNotifications || 0; if (badge) { badge.textContent = count > 0 ? String(count) : ''; badge.hidden = count === 0; } }); } async function renderNotifications() { var list = $('#notif-list'), countEl = $('#notif-count'); var projSel = $('#notif-project'), sevSel = $('#notif-severity'), catSel = $('#notif-category'); var st = { project: '', severity: '', category: '', status: 'all' }; var notifications = []; var draw = function() { var shown = notifications; if (st.project) shown = shown.filter(function(n) { return n.projectId === st.project; }); if (st.severity) shown = shown.filter(function(n) { return n.severity === st.severity; }); if (st.category) shown = shown.filter(function(n) { return n.category === st.category; }); if (st.status !== 'all') shown = shown.filter(function(n) { return n.status === st.status; }); $$('.tabs button', list.closest('.wrap')).forEach(function(b) { b.setAttribute('aria-pressed', String(b.dataset.status === st.status)); }); countEl.textContent = plural(shown.length, 'notification'); fill(list, shown.length ? shown.map(notifRow) : h('div', { class: 'empty', style: 'padding:40px 16px' }, icon('bell'), h('h3', { text: 'No notifications' }), h('p', { class: 'muted', text: 'Events will appear here as work moves through the pipeline.' }))); }; if (projSel) projSel.addEventListener('change', function() { st.project = projSel.value; draw(); }); if (sevSel) sevSel.addEventListener('change', function() { st.severity = sevSel.value; draw(); }); if (catSel) catSel.addEventListener('change', function() { st.category = catSel.value; draw(); }); $$('.tabs button').forEach(function(b) { b.addEventListener('click', function() { st.status = b.dataset.status; draw(); }); }); var markAllBtn = $('#mark-all-read'); if (markAllBtn) markAllBtn.addEventListener('click', async function() { await fetch(url('/api/notifications/mark-read'), { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ all: true }) }); notifications.forEach(function(n) { n.status = 'read'; }); draw(); updateNotifBadge(); toast('All notifications marked as read.'); }); try { var data = await getJson('/api/notifications'); notifications = data.notifications || []; await loadProjects(); fill(projSel, [h('option', { value: '', text: 'All projects' })].concat(PROJECTS.map(function(p) { return h('option', { value: p.id, text: p.displayName }); }))); fill(catSel, [h('option', { value: '', text: 'All categories' })].concat(NOTIF_CATEGORIES.map(function(c) { return h('option', { value: c, text: c }); }))); draw(); footer(); } catch (e) { fill(list, errorBox(e.message)); } } setupTheme(); const pendingToast = sessionStorage.getItem('factory:toast'); if (pendingToast) { sessionStorage.removeItem('factory:toast'); toast(pendingToast); } setupCreate(); RENDER = { overview: renderOverview, board: renderBoard, plans: renderPlans, work: renderWork, projects: renderProjects, 'project-detail': renderProjectDetail, notifications: renderNotifications, settings: renderSettings }[VIEW] || null; if (RENDER) RENDER(); if (VIEW === 'manage') setupManage(); if (VIEW === 'settings') setupOfflineSettings(); readCachedData(); if (DATA && DATA.settings) updateKillSwitchBanner(DATA.settings.killSwitch); fetchData().then(function(d) { if (d && d.settings) updateKillSwitchBanner(d.settings.killSwitch); var badge = document.querySelector('.nav a[href*="notifications"] .notif-badge'); if (badge && d) { var uc = d.unreadNotifications || 0; badge.textContent = uc > 0 ? String(uc) : ''; badge.hidden = uc === 0; } }).catch(function() {}); setNet(); flushDraft(); setupServiceWorker(); function setupOfflineSettings() { const clear = $('#clear-offline'); if (clear) clear.addEventListener('click', async () => { clearCachedData(); try { if (window.caches) { const keys = await caches.keys(); await Promise.all(keys.filter((k) => k.indexOf('kody-factory-') === 0).map((k) => caches.delete(k))); } } catch (e) {} setNet(); toast('Cleared cached data on this device.'); }); const install = $('#install-app'); if (install && INSTALL.prompt) install.hidden = false; if (install) install.addEventListener('click', async () => { if (!INSTALL.prompt) return; INSTALL.prompt.prompt(); try { await INSTALL.prompt.userChoice; } catch (e) {} INSTALL.prompt = null; install.hidden = true; }); } // Service worker: off on localhost unless ?sw=1 (dev/test opt-in). An update // waits until you tap Refresh; drafts are already saved. Refresh always asks the // registration for the worker that is waiting right now (an older waiting worker // goes redundant when a newer publish lands), tells it to take over, and reloads // on controllerchange, or after a short timeout if that never fires. The banner // shows only while a worker is really waiting behind the current controller. const SW_RELOAD_TIMEOUT_MS = 4000; function setupServiceWorker() { if (!('serviceWorker' in navigator)) return; const local = /^(localhost|127\.0\.0\.1|\[::1\])$/.test(location.hostname); if (local && new URLSearchParams(location.search).get('sw') !== '1' && sessionStorage.getItem('factory:sw') !== '1') return; if (local) sessionStorage.setItem('factory:sw', '1'); let accepted = false, reloaded = false, regRef = null; const reload = () => { if (reloaded) return; reloaded = true; location.reload(); }; const sync = () => { const w = regRef && regRef.waiting; const next = w && navigator.serviceWorker.controller && w !== navigator.serviceWorker.controller ? w : null; if (NET.update !== next) { NET.update = next; setNet(); } }; navigator.serviceWorker.addEventListener('controllerchange', () => { if (accepted) { reload(); return; } sync(); }); const activate = (w) => { accepted = true; try { w.postMessage({ type: 'SKIP_WAITING' }); } catch (e) { /* fall through to the timeout */ } try { w.postMessage('SKIP_WAITING'); } catch (e) { /* older workers read the string form */ } setTimeout(reload, SW_RELOAD_TIMEOUT_MS); }; $('#net-action').addEventListener('click', async () => { const btn = $('#net-action'); btn.disabled = true; btn.textContent = 'Updating'; try { const reg = regRef || await navigator.serviceWorker.getRegistration(BP + '/'); if (reg && reg.waiting) { activate(reg.waiting); return; } if (reg) { await reg.update().catch(() => {}); if (reg.waiting) { activate(reg.waiting); return; } if (reg.installing) { const w = reg.installing; w.addEventListener('statechange', () => { if (w.state === 'installed') activate(w); }); setTimeout(reload, SW_RELOAD_TIMEOUT_MS * 2); return; } } } catch (e) { /* reload below */ } reload(); }); const track = (w) => { if (!w) return; w.addEventListener('statechange', sync); }; navigator.serviceWorker.register(url('/sw.js'), { scope: BP + '/', updateViaCache: 'none' }).then((reg) => { regRef = reg; track(reg.waiting); track(reg.installing); sync(); reg.addEventListener('updatefound', () => track(reg.installing)); document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'visible') reg.update().then(sync, () => {}); }); }).catch(() => {}); } `