Skip to content
← Public packages

@kody/kody-factory

Forkable multi-project software factory: signals, priority queue, project UI, sweep job. Agent runners and Sentry reach it by events.

FollowFork

Files

ui.ts

454 lines · 34.7 KB · TypeScript
/**
 * Server-rendered HTML for the factory app: shared shell, per-view skeletons,
 * and the no-JS manage page. Pure (no kody:runtime) so it is unit-testable.
 */
import { CSS } from './styles.ts'
import { CLIENT_JS } from './client.ts'
import { THEME_BOOT_JS } from './theme.ts'
import type { ProjectConfig } from '../projects/model.ts'

export type View = 'overview' | 'board' | 'work' | 'plans' | 'projects' | 'project-detail' | 'notifications' | 'health' | 'signals' | 'reports' | 'settings' | 'manage'

export const ICONS: Record<string, string> = {
	overview: '<rect x="3" y="3" width="7" height="7" rx="1.5"/><rect x="14" y="3" width="7" height="7" rx="1.5"/><rect x="3" y="14" width="7" height="7" rx="1.5"/><rect x="14" y="14" width="7" height="7" rx="1.5"/>',
	queue: '<path d="M8 6h13M8 12h13M8 18h13M3.5 6h.01M3.5 12h.01M3.5 18h.01"/>',
	folder: '<path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z"/>',
	settings: '<path d="M4 6h10M18 6h2M4 12h4M12 12h8M4 18h12"/><circle cx="16" cy="6" r="2"/><circle cx="10" cy="12" r="2"/><circle cx="18" cy="18" r="2"/>',
	plus: '<path d="M12 5v14M5 12h14"/>',
	inbox: '<path d="M3 13h5l1.5 3h5L16 13h5"/><path d="M5.5 5h13L21 13v5a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5z"/>',
	search: '<circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/>',
	close: '<path d="M6 6l12 12M18 6 6 18"/>',
	eye: '<path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7S2 12 2 12z"/><circle cx="12" cy="12" r="3"/>',
	alert: '<path d="M12 9v4M12 17h.01"/><path d="M10.3 3.9 1.8 18a2 2 0 0 0 1.7 3h17a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z"/>',
	message: '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
	branch: '<circle cx="6" cy="6" r="2.5"/><circle cx="6" cy="18" r="2.5"/><circle cx="18" cy="8" r="2.5"/><path d="M6 8.5v7M18 10.5a6 6 0 0 1-6 6H8.5"/>',
	zap: '<path d="M13 2 4 14h7l-1 8 9-12h-7z"/>',
	pencil: '<path d="M4 20h4L19 9l-4-4L4 16z"/>',
	mail: '<rect x="3" y="5" width="18" height="14" rx="2"/><path d="m3 7 9 6 9-6"/>',
	external: '<path d="M14 4h6v6M20 4l-9 9M18 14v5a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V7a1 1 0 0 1 1-1h5"/>',
	check: '<path d="m5 12 5 5 9-10"/>',
	arrow: '<path d="M5 12h14M13 6l6 6-6 6"/>',
	sun: '<circle cx="12" cy="12" r="4"/><path d="M12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4"/>',
	moon: '<path d="M20.5 13.4A8.5 8.5 0 1 1 10.6 3.5a6.6 6.6 0 0 0 9.9 9.9z"/>',
	pulse: '<path d="M3 12h4l2.5-7 5 14 2.5-7h4"/>',
	monitor: '<rect x="3" y="4" width="18" height="12" rx="2"/><path d="M8 20h8M12 16v4"/>',
	bell: '<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.73 21a2 2 0 0 1-3.46 0"/>',
	kanban: '<rect x="3" y="3" width="5" height="13" rx="1"/><rect x="10" y="3" width="5" height="8" rx="1"/><rect x="17" y="3" width="5" height="18" rx="1"/>',
	compass: '<circle cx="12" cy="12" r="9"/><polygon points="16.2,7.8 14.3,14.3 7.8,16.2 9.7,9.7"/>',
	clock: '<circle cx="12" cy="12" r="9"/><path d="M12 7v5l3 3"/>',
	move: '<path d="M5 9l-3 3 3 3M9 5l3-3 3 3M15 19l-3 3-3-3M19 9l3 3-3 3M2 12h20M12 2v20"/>',
	report: '<path d="M7 3h7l5 5v13a1 1 0 0 1-1 1H7a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1z"/><path d="M14 3v5h5M9 13h6M9 17h4"/>',
	grip: '<circle cx="9" cy="5" r="1"/><circle cx="15" cy="5" r="1"/><circle cx="9" cy="12" r="1"/><circle cx="15" cy="12" r="1"/><circle cx="9" cy="19" r="1"/><circle cx="15" cy="19" r="1"/>',
}

/** Standalone favicon document: same art as APP_MARK_SVG and public/favicon.svg. */
export function faviconSvg(): string {
	return APP_MARK_SVG.replace('<svg viewBox', '<svg xmlns="http://www.w3.org/2000/svg" viewBox')
		.replace(' aria-hidden="true"', '')
		.replace(/kf-mark-grad/g, 'kf-favicon-grad')
}

export function icon(name: string): string {
	return `<svg class="icon" viewBox="0 0 24 24" aria-hidden="true">${ICONS[name] ?? ''}</svg>`
}

export function esc(s: unknown): string {
	return String(s ?? '')
		.replace(/&/g, '&amp;')
		.replace(/</g, '&lt;')
		.replace(/>/g, '&gt;')
		.replace(/"/g, '&quot;')
		.replace(/'/g, '&#39;')
}

/** Factory mark: tiles moving along a line. Same art as public/favicon.svg (unique gradient id for inline use). */
export const APP_MARK_SVG = `<svg viewBox="0 0 32 32" aria-hidden="true"><defs><linearGradient id="kf-mark-grad" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stop-color="#6d6af5"/><stop offset="1" stop-color="#4338ca"/></linearGradient></defs><rect width="32" height="32" rx="8" fill="url(#kf-mark-grad)"/><g fill="#fff"><rect x="4.5" y="11.5" width="6.5" height="6.5" rx="1.5" fill-opacity=".45"/><rect x="12.75" y="9.5" width="6.5" height="8.5" rx="1.5" fill-opacity=".72"/><rect x="21" y="7.5" width="6.5" height="10.5" rx="1.5"/><circle cx="8.5" cy="24.75" r="1.35" fill-opacity=".7"/><circle cx="16" cy="24.75" r="1.35" fill-opacity=".7"/><circle cx="23.5" cy="24.75" r="1.35" fill-opacity=".7"/></g><path d="M4 21h24" stroke="#fff" stroke-width="2.2" stroke-linecap="round"/></svg>`

const NAV: Array<[View, string, string, string]> = [
	['overview', '/', 'Overview', 'overview'],
	['board', '/board', 'Board', 'kanban'],
	['plans', '/plans', 'Plans', 'compass'],
	['work', '/work', 'Work queue', 'queue'],
	['reports', '/reports', 'Reports', 'report'],
	['projects', '/projects', 'Projects', 'folder'],
	['notifications', '/notifications', 'Notifications', 'bell'],
	['health', '/factory-health', 'Health', 'pulse'],
	['signals', '/signals', 'Signals', 'zap'],
]

/** Overview placeholders use the real row/card markup with hidden text so data lands in the same boxes. */
export const PH_ROW = `<div class="row slot-ph" aria-hidden="true"><span class="src ph-box"></span><span><span class="row-title ph">Loading work item</span><span class="row-meta"><span class="ph">Project</span></span></span><span class="chip ph">New</span></div>`
const PH_PCARD = `<article class="card pcard" aria-hidden="true"><div class="ptop"><span class="mono ph-box"></span><div><h3 class="ph">Project</h3><code class="ph">project</code></div></div><div class="stack" style="gap:6px"><span class="ph small">owner/repository</span></div><div class="pmeta"><span class="chip ph">Devin</span><span class="chip ph">Enabled</span></div></article>`
const SKEL_ROW = `<div class="row skel-row" aria-hidden="true"><div class="skel" style="height:30px;width:30px"></div><div class="skel" style="height:36px;width:100%"></div></div>`
/** Same markup and typical copy as the client's kv rows, shown as skeletons so the real rows land in the same space. */
const skelKv = (rows: Array<[string, string, string]>) =>
	`<ul class="kv is-skel" aria-hidden="true">${rows.map(([t, d, c]) => `<li><div><b>${t}</b><span class="d">${d}</span></div><span class="chip">${c}</span></li>`).join('')}</ul>`
const RUN_SAFELY_SKEL: Array<[string, string, string]> = [
	['Shadow mode', 'Agent sessions can start for ready work.', 'Off'],
	['Max concurrent sessions', 'Up to 2 agent sessions at a time.', '2'],
	['Merge policy', 'Every merge stays with you.', "Agents can't merge"],
	['Sweep', 'Every 15 minutes. Moves each item at most one stage per run.', 'Scheduled'],
	['Pilot scope', 'Sweep, backfill, and issue intake act on no project until a pilot scope is set.', 'Not set'],
]
const CONNECTIONS_SKEL: Array<[string, string, string]> = [
	['Devin', 'Agent runner for building work.', 'Configured'],
	['Cloudflare AI', 'Model used to triage new work.', 'Account configured'],
	['GitHub intake', 'Issue and CI webhooks are declared and need your approval before events arrive.', 'Setup required'],
	['GitHub issue backfill', 'Preview open issues from enabled repositories, then add them in shadow mode. Runs only when you ask.', 'On demand'],
	['GitHub Projects', 'Planning board updates are turned off.', 'Not connected'],
]
const skel = (h: number, w = '100%') => `<div class="skel" style="height:${h}px;width:${w}"></div>`

function navLink(bp: string, current: View, [view, href, label, ic]: [View, string, string, string]) {
	const active = current === view || (view === 'settings' && current === 'manage')
	const badge = view === 'notifications' ? '<span class="notif-badge" hidden></span>' : ''
	return `<a href="${bp}${href}"${active ? ' aria-current="page"' : ''}>${icon(ic)}<span>${label}</span>${badge}</a>`
}

function overviewMain(bp: string): string {
	return `
<section class="hero">
 <div>
  <span id="shadow-badge" class="badge" hidden>Shadow mode</span>
  <h1>Move work forward.</h1>
  <p>Track priorities, see what needs attention, and keep work moving.</p>
 </div>
 <div class="actions">
  <a class="btn primary" href="${bp}/board">${icon('kanban')}Open board</a>
  <button type="button" class="btn" data-open-create>${icon('plus')}Add work</button>
 </div>
</section>
<div id="shadow-note" class="notice" hidden>${icon('eye')}<div><strong>Shadow mode is on</strong><p>The factory is observing only. New work stays parked before a Devin session starts. <a href="${bp}/settings">Manage settings</a></p></div></div>
<section aria-labelledby="stats-h"><h2 id="stats-h" class="sr">Key numbers</h2>
 <div class="stats" id="stats">${['Active projects', 'Needs your attention', 'In progress', 'Open work'].map((l) => `<div class="stat" aria-hidden="true"><span>${l}</span><b class="ph">0</b><small class="ph">Loading</small></div>`).join('')}</div>
</section>
<div class="grid2">
 <section class="card" aria-labelledby="next-h"><div class="card-head"><h2 id="next-h">Up next</h2><a class="link" href="${bp}/work">Open work queue</a></div><div id="overview-queue"><div class="list slots">${PH_ROW.repeat(5)}</div><div class="statusline" aria-hidden="true"><span class="dot"></span><span class="ph">Loading projects</span></div></div></section>
 <section class="card" aria-labelledby="prio-h"><div class="card-head"><h2 id="prio-h">Priority snapshot</h2></div><div id="prio" class="bars" aria-hidden="true">${['P0', 'P1', 'P2', 'P3', 'Not set'].map((l) => `<div class="bar-row"><span>${l}</span><div class="bar"></div><b class="ph">0</b></div>`).join('')}</div></section>
</div>
<section id="overview-stalled-section" class="card" hidden aria-labelledby="stalled-h"><div class="card-head"><h2 id="stalled-h">Stalled</h2><a class="link" href="${bp}/board?stalledOnly=1">View all on board</a></div><div id="overview-stalled"></div></section>
<section aria-labelledby="proj-h"><div class="card-head"><h2 id="proj-h">Projects</h2><a class="link" id="projects-link" href="${bp}/projects">All projects</a></div>
 <div class="pcards" id="overview-projects">${PH_PCARD.repeat(3)}</div>
</section>`
}

function boardMain(bp: string): string {
	return `
<header class="page-head"><div><h1>Board</h1><p>See where every piece of work is in the ship pipeline.</p></div>
 <div class="toolbar">
  <label><span class="sr">Filter by project</span><select id="board-project"><option value="">All projects</option></select></label>
  <label class="check"><input type="checkbox" id="board-stalled-only"/>Stalled only</label>
  <label class="check"><input type="checkbox" id="board-show-dropped"/>Show dropped</label>
 </div>
</header>
<div id="board-category-chips" class="category-chips" role="group" aria-label="Filter by category"></div>
<div id="board-pipe-strip" class="pipe-strip" role="group" aria-label="Pipeline summary"></div>
<div id="board-mobile-tabs" class="tabs board-col-tabs" role="group" aria-label="Board columns" hidden></div>
<div class="board-scroll" id="board-scroll">
 <div class="board" id="board" role="region" aria-label="Work pipeline board">
  <div class="board-skel" aria-hidden="true">${Array.from({ length: 7 }, () => `<div class="bcol"><div class="bcol-head"><div class="skel" style="height:20px;width:80px"></div></div><div class="skel" style="height:90px;border-radius:12px"></div></div>`).join('')}</div>
 </div>
</div>`
}

function plansMain(bp: string): string {
	return `
<header class="page-head"><div><h1>Plans</h1><p>What to build and why. The source of truth for decisions.</p></div>
 <div class="actions"><button type="button" class="btn primary" id="create-plan-btn">${icon('plus')}New plan</button></div>
</header>
<div class="toolbar">
 <label><span class="sr">Filter by project</span><select id="plans-project"><option value="">All projects</option></select></label>
 <label class="check"><input type="checkbox" id="plans-show-archived"/>Show archived</label>
</div>
<div id="plans-mobile-tabs" class="tabs board-col-tabs" role="group" aria-label="Plan columns" hidden></div>
<div class="board-scroll" id="plans-scroll">
 <div class="board" id="plans-board" role="region" aria-label="Plans board">
  <div class="board-skel" aria-hidden="true">${Array.from({ length: 5 }, () => `<div class="bcol"><div class="bcol-head"><div class="skel" style="height:20px;width:80px"></div></div><div class="skel" style="height:90px;border-radius:12px"></div></div>`).join('')}</div>
 </div>
</div>
<dialog id="plan-dialog" aria-labelledby="plan-title"><div class="dlg" id="plan-body"></div></dialog>
<dialog id="plan-edit-dialog" aria-labelledby="plan-edit-title">
 <form id="plan-edit-form" class="dlg" novalidate>
  <div class="dlg-head"><div><h2 id="plan-edit-title">New plan</h2></div>
   <button type="button" class="icon-btn" data-close aria-label="Close">${icon('close')}</button></div>
  <div class="form-grid">
   <label class="field full">Title<input name="title" required maxlength="200" placeholder="What are you building?"/></label>
   <label class="field">Status<select name="status"><option value="exploring">Exploring</option><option value="proposed">Proposed</option><option value="decided">Decided</option><option value="in-progress">In progress</option><option value="shipped">Shipped</option></select></label>
   <label class="field">Priority<select name="priority"><option value="">Not set</option><option value="0">P0</option><option value="1">P1</option><option value="2">P2</option><option value="3">P3</option></select></label>
   <label class="field full">Body <small>Markdown. The living plan.</small><textarea name="body" rows="8" maxlength="50000"></textarea></label>
  </div>
  <p class="err" id="plan-edit-error" role="alert" hidden></p>
  <div class="dlg-foot"><button type="button" class="btn" data-close>Cancel</button><button type="submit" class="btn primary">Save</button></div>
 </form>
</dialog>`
}

function notificationsMain(bp: string): string {
	return `
<header class="page-head"><div><h1>Notifications</h1><p>Events from across the factory.</p></div>
 <div class="actions"><button type="button" class="btn" id="mark-all-read">Mark all read</button></div>
</header>
<div class="toolbar">
 <label><span class="sr">Filter by project</span><select id="notif-project"><option value="">All projects</option></select></label>
 <label><span class="sr">Filter by severity</span><select id="notif-severity"><option value="">All severities</option><option value="error">Error</option><option value="warning">Warning</option><option value="info">Info</option></select></label>
 <label><span class="sr">Filter by category</span><select id="notif-category"><option value="">All categories</option></select></label>
 <div class="tabs" role="group" aria-label="Status">
  <button type="button" data-status="all" aria-pressed="true">All</button>
  <button type="button" data-status="unread" aria-pressed="false">Unread</button>
  <button type="button" data-status="read" aria-pressed="false">Read</button>
 </div>
</div>
<p id="notif-count" class="muted small" aria-live="polite">Loading notifications...</p>
<div id="notif-list" class="list">${Array.from({ length: 4 }, () => `<div class="row skel-row" aria-hidden="true"><div class="skel" style="height:30px;width:30px"></div><div class="skel" style="height:36px;width:100%"></div></div>`).join('')}</div>`
}

function projectDetailMain(bp: string): string {
	const skelCard = (title: string) => `<section class="card stack" aria-label="${title}"><h2>${title}</h2><div class="skel" style="height:120px"></div></section>`
	return `
<div class="crumb"><a href="${bp}/projects">Projects</a><span>/</span><span id="pd-crumb" class="ph">Project</span></div>
<header class="page-head" id="pd-head"><div><h1 id="pd-title" class="ph">Loading project</h1><p id="pd-sub" class="ph muted">Loading</p></div>
 <div class="actions" id="pd-actions"></div>
</header>
<div id="pd-badges" style="display:flex;gap:8px;flex-wrap:wrap"></div>
<div class="pd-grid" id="pd-grid">
 ${skelCard('Agents')}
 ${skelCard('Automated runs')}
 ${skelCard('Flow metrics')}
 ${skelCard('PRs and CI')}
</div>`
}

function workMain(bp: string): string {
	const tabs = [['all', 'All'], ['active', 'Active'], ['needs', 'Needs you'], ['complete', 'Complete']]
	return `
<header class="page-head"><div><h1>Work queue</h1><p>One place for everything moving through your factory.</p></div>
 <button type="button" class="btn primary" data-open-create>${icon('plus')}Add work</button></header>
<section aria-label="Work items" class="stack">
 <div class="toolbar">
  <label class="search"><span class="sr">Search work</span>${icon('search')}<input id="work-search" type="search" placeholder="Search work…" autocomplete="off"/></label>
  <label><span class="sr">Filter by project</span><select id="work-project"><option value="">All projects</option></select></label>
  <div class="tabs" role="group" aria-label="Filter by status">${tabs.map(([v, l]) => `<button type="button" data-status="${v}" aria-pressed="${v === 'all'}">${l}</button>`).join('')}</div>
 </div>
 <p id="work-count" class="muted small" aria-live="polite">Loading work…</p>
 <div class="work-slot"><div id="work-list" class="list">${SKEL_ROW.repeat(6)}</div></div>
</section>
<p class="small muted">Looking for setup? <a href="${bp}/manage">Manage projects</a></p>`
}

function projectsMain(bp: string): string {
	return `
<header class="page-head"><div><h1>Projects</h1><p>Every repository the factory can pick up work from.</p></div>
 <a class="btn" href="${bp}/manage">Manage projects</a></header>
<section aria-label="Projects" class="stack">
 <label class="search" style="max-width:420px"><span class="sr">Search projects</span>${icon('search')}<input id="project-search" type="search" placeholder="Search projects…" autocomplete="off"/></label>
 <div id="projects-banner"></div>
 <div class="pgrid" id="projects-grid"><div class="card">${skel(90)}</div><div class="card">${skel(90)}</div></div>
</section>`
}

function settingsMain(bp: string): string {
	return `
<header class="page-head"><div><h1>Settings</h1><p>How the factory runs, and what it's connected to.</p></div></header>
<div class="settings">
 <section class="card" aria-labelledby="run-h"><div class="card-head"><h2 id="run-h">Run safely</h2></div><div id="run-safely">${skelKv(RUN_SAFELY_SKEL)}</div></section>
 <section class="card" aria-labelledby="conn-h"><div class="card-head"><h2 id="conn-h">Connections</h2></div>
  <p class="muted small" style="margin:-8px 0 14px">Credentials are managed in Kody. No secrets appear here.</p><div id="connections">${skelKv(CONNECTIONS_SKEL)}</div></section>
 <section class="card stack" aria-labelledby="ps-h"><h2 id="ps-h">Project settings</h2><p class="muted">Add projects and repositories, turn them on or off, or set the model triage account.</p><div><a class="btn" href="${bp}/manage">Manage projects</a></div></section>
 <section class="card stack" aria-labelledby="od-h"><h2 id="od-h">Offline and install</h2><p class="muted">This browser keeps the last queue snapshot (titles, projects, states; no settings or account IDs) so the app opens offline, marked with when it last synced. Drafts of new work wait here until you reconnect. Changes to projects, settings, and backfill need a connection.</p><div class="row-btns"><button type="button" class="btn" id="clear-offline">Clear cached data</button><button type="button" class="btn" id="install-app" hidden>Install app</button></div></section>
 <section class="card stack needs-js" aria-labelledby="push-h"><h2 id="push-h">Push notifications</h2><p class="muted">Get a phone or desktop notification for new Sentry and signal cards and anything that needs you. Each device asks once. Tapping a notification opens the card.</p><div id="push-status" class="small muted">Checking this device...</div><ul class="kv" id="push-devices"></ul><div class="row-btns"><button type="button" class="btn" id="push-enable" hidden>Allow on this device</button><button type="button" class="btn" id="push-test" hidden>Send test push</button><button type="button" class="btn" id="push-disable" hidden>Turn off on this device</button></div></section>
 <section class="card stack" aria-labelledby="ks-h"><h2 id="ks-h">Kill switch</h2><p class="muted">When engaged, the factory will not start new agent runs or merges. Sweeps still run but skip all transitions.</p><div class="row-btns"><button type="button" class="btn" id="kill-switch-toggle">Loading...</button></div></section>
 <section class="card stack" aria-labelledby="cf-h"><h2 id="cf-h">Config export and import</h2><p class="muted">Export the factory configuration as a JSON document (no secrets). Import a config to preview and apply changes.</p><div class="row-btns"><button type="button" class="btn" id="config-export-btn">${icon('arrow')}Export config</button><label class="btn"><input type="file" accept=".json,application/json" id="config-import-file" hidden/>Import config</label></div><div id="config-import-preview" hidden></div></section>
 <section class="card stack" aria-labelledby="tpl-h"><h2 id="tpl-h">Templates</h2><p class="muted">Apply a built-in template to set up projects and settings.</p><div id="templates-list">Loading templates...</div></section>
 <section class="card stack" aria-labelledby="mc-h"><h2 id="mc-h">Model check</h2><p class="muted">Confirm triage can reach its model. It runs only when you click it.</p><div><a class="btn" href="${bp}/manage#model">Check model connection</a></div></section>
 <section class="card stack needs-js appearance" aria-labelledby="ap-h"><h2 id="ap-h">Appearance</h2><p class="muted">Saved in this browser only.</p>${themeChoices('theme-settings', 'Theme')}</section>
</div>`
}

const THEME_CHOICES: Array<[string, string, string, string]> = [
	['light', 'Light', 'Always use the light theme', 'sun'],
	['dark', 'Dark', 'Always use the dark theme', 'moon'],
	['system', 'System', 'Match your device setting', 'monitor'],
]

/** Native radio group (arrow keys work); client.ts syncs every group on the page. */
export function themeChoices(name: string, legend: string): string {
	return `<fieldset class="theme-group"><legend>${legend}</legend>${THEME_CHOICES.map(
		([v, label, sub, ic]) =>
			`<label class="theme-opt"><input type="radio" name="${name}" value="${v}" data-theme-choice/>${icon(ic)}<span><b>${label}</b><small>${sub}</small></span></label>`,
	).join('')}</fieldset>`
}

const THEME_CONTROL = `<div class="theme" id="theme">
 <button type="button" class="theme-btn" id="theme-btn" aria-expanded="false" aria-controls="theme-menu" title="Theme">
  <span class="theme-ic" data-ic="light">${icon('sun')}</span><span class="theme-ic" data-ic="dark">${icon('moon')}</span><span class="theme-ic" data-ic="system">${icon('monitor')}</span>
  <span class="theme-text">Theme</span><span class="theme-label" id="theme-label"></span>
 </button>
 <div class="theme-menu" id="theme-menu" hidden>${themeChoices('theme-nav', 'Appearance')}</div>
</div>`

const STATIC_DIALOGS = `
<dialog id="create-dialog" aria-labelledby="create-title">
 <form id="create-form" class="dlg" novalidate>
  <div class="dlg-head"><div><h2 id="create-title">Add work</h2><p class="muted small">It joins the queue as New. Nothing starts automatically.</p></div>
   <button type="button" class="icon-btn" data-close aria-label="Close">${icon('close')}</button></div>
  <div class="form-grid">
   <label class="field">Project<select name="projectId" id="cf-project" required></select></label>
   <label class="field">Type<select name="kind"><option value="general">General task</option><option value="friction">Friction</option><option value="feedback">Feedback</option></select></label>
   <label class="field full">Title<input name="title" required maxlength="200" placeholder="What needs to happen?"/></label>
   <label class="field full">Details <small>Optional. Context, links, or acceptance notes.</small><textarea name="body" maxlength="8000"></textarea></label>
   <label class="field">Priority<select name="priority"><option value="">Not set</option><option value="0">P0 · Urgent</option><option value="1">P1 · High</option><option value="2">P2 · Normal</option><option value="3">P3 · Low</option></select></label>
   <label class="field">Repository<select name="repoRef" id="cf-repo"></select></label>
  </div>
  <p class="err" id="create-error" role="alert" hidden></p>
  <div class="dlg-foot"><button type="button" class="btn" data-close>Cancel</button><button type="submit" class="btn primary">Add to queue</button></div>
 </form>
</dialog>
<dialog id="item-dialog" aria-labelledby="item-title"><div class="dlg" id="item-body"></div></dialog>
<dialog id="confirm-dialog" aria-labelledby="confirm-title"><div class="dlg">
 <h2 id="confirm-title">Are you sure?</h2><p id="confirm-text" class="muted"></p>
 <div class="dlg-foot"><button type="button" class="btn" data-close>Cancel</button><button type="button" class="btn primary" id="confirm-ok">Confirm</button></div>
</div></dialog>
<div id="toast" class="toast" role="status" aria-live="polite" hidden></div>
<div id="net" class="net" role="status" aria-live="polite"><span class="net-dot" aria-hidden="true"></span><span id="net-text"></span><button type="button" class="net-btn" id="net-action" hidden></button></div>`

export function renderShell(opts: { basePath: string; view: View; title: string; main?: string }): string {
	const bp = esc(opts.basePath)
	const main =
		opts.main ??
		{ overview: overviewMain, board: boardMain, plans: plansMain, work: workMain, projects: projectsMain, 'project-detail': projectDetailMain, notifications: notificationsMain, settings: settingsMain, health: () => '', signals: () => '', reports: () => '', manage: () => '' }[opts.view](bp)
	const icons = JSON.stringify(ICONS).replace(/</g, '\\u003c')
	return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width,initial-scale=1"/>
<script>${THEME_BOOT_JS}</script>
<title>${esc(opts.title)} · Kody Factory</title>
<link rel="icon" type="image/svg+xml" href="${bp}/_assets/favicon.svg"/>
<link rel="apple-touch-icon" href="${bp}/_assets/apple-touch-icon.png"/>
<meta name="theme-color" content="#111827"/>
<link rel="manifest" href="${bp}/manifest.webmanifest" crossorigin="use-credentials"/>
<style>${CSS}</style>
</head>
<body data-base="${bp}" data-view="${opts.view}">
<a class="skip" href="#main">Skip to content</a>
<div class="app">
 <aside class="rail">
  <a class="brand" href="${bp}/" aria-label="Kody Factory home">${APP_MARK_SVG}<div><b>Kody</b><span>Factory</span></div></a>
  <nav class="nav" aria-label="Main">${NAV.map((n) => navLink(bp, opts.view, n)).join('')}</nav>
  <div class="rail-bottom">${THEME_CONTROL}
  <nav class="nav nav-util" aria-label="Settings">${navLink(bp, opts.view, ['settings', '/settings', 'Settings', 'settings'])}</nav></div>
 </aside>
 <main id="main" class="main" tabindex="-1">
  <div id="kill-switch-banner" class="notice kill-banner" hidden>${icon('alert')}<div><strong>Factory paused</strong><p>The kill switch is on. No new agent runs or merges will start. <a href="${bp}/settings">Manage settings</a></p></div></div>
  <div class="wrap">${main}</div>
  <footer class="foot"><span id="configured-for">Kody Factory</span><span>Times shown in Mountain Time (America/Denver)</span></footer>
 </main>
</div>
${STATIC_DIALOGS}
<script type="application/json" id="icons">${icons}</script>
<script type="module">${CLIENT_JS}</script>
</body>
</html>`
}

const BAD_FLASH = /^(error|invalid|delete aborted|unknown)/i

export function renderManage(opts: {
	basePath: string
	projects: ProjectConfig[]
	flash?: string
	modelAccountSet: boolean
}): string {
	const bp = esc(opts.basePath)
	const flash = opts.flash
		? `<div class="flash${BAD_FLASH.test(opts.flash) ? ' bad' : ''}" role="status">${esc(opts.flash)}</div>`
		: ''
	const options = opts.projects
		.map((p) => `<option value="${esc(p.id)}">${esc(p.displayName)} (${esc(p.id)})</option>`)
		.join('')
	const post = (fields: Record<string, string>, label: string, cls = 'btn small', confirm?: string) =>
		`<form class="inline" method="post" action="${bp}/manage"${confirm ? ` data-confirm="${esc(confirm)}"` : ''}>${Object.entries(
			fields,
		)
			.map(([k, v]) => `<input type="hidden" name="${k}" value="${esc(v)}"/>`)
			.join('')}<button type="submit" class="${cls}">${label}</button></form>`
	const rows = opts.projects
		.map((p) => {
			const repos = p.repos
				.map(
					(r) => `<li><span class="repo">${esc(r.repoRef)}</span><span class="chip ${r.enabled ? 'on' : 'off'}">${r.enabled ? 'On' : 'Off'}</span>${post(
						{ action: r.enabled ? 'disable-repo' : 'enable-repo', projectId: p.id, repoRef: r.repoRef },
						r.enabled ? 'Turn off repo' : 'Turn on repo',
						'btn small',
						r.enabled ? `Turn off ${r.repoRef}? The factory stops accepting new work from this repository. Existing work stays in the queue.` : undefined,
					)}</li>`,
				)
				.join('')
			return `<div class="prow"><div><div class="ptop"><div><h3>${esc(p.displayName)} <span class="chip ${p.enabled ? 'on' : 'off'}">${p.enabled ? 'Enabled' : 'Disabled'}</span></h3><code>${esc(p.id)}</code></div></div>
<ul class="repos">${repos || '<li class="muted small">No repositories yet</li>'}</ul></div>
<div class="actions"><a class="btn small" href="${bp}/work?project=${encodeURIComponent(p.id)}">View work</a>${post(
				{ action: p.enabled ? 'disable-project' : 'enable-project', projectId: p.id },
				p.enabled ? 'Disable' : 'Enable',
				'btn small',
				p.enabled ? `Disable ${p.displayName}? The sweep stops advancing its work and no new work is accepted. Nothing is deleted.` : undefined,
			)}</div></div>`
		})
		.join('')
	const main = `
<header class="page-head"><div><h1>Manage projects</h1><p>Keep your projects and connections up to date.</p></div></header>
${flash}
<div class="manage">
 <section class="card wide" aria-labelledby="yp-h"><div class="card-head"><h2 id="yp-h">Your projects</h2><span class="muted small">${opts.projects.length} configured</span></div>${rows || '<p class="muted">No projects yet. Add one below.</p>'}</section>
 <section class="card" aria-labelledby="ap-h"><h2 id="ap-h">Add a project</h2><p class="muted small" style="margin:6px 0 16px">Saving an existing project ID replaces its settings.</p>
  <form method="post" action="${bp}/manage" class="stack">
   <input type="hidden" name="action" value="upsert-project"/>
   <label class="field">Project ID <small>Lowercase letters, numbers, - or _</small><input name="id" required pattern="[a-z][a-z0-9_-]{0,63}" placeholder="my-app"/></label>
   <label class="field">Display name<input name="displayName" placeholder="My App"/></label>
   <label class="field">GitHub repository<input name="repoRef" pattern="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+" placeholder="owner/repo"/></label>
   <label class="field">Runner<select name="defaultRunnerId"><option value="devin">Devin</option><option value="single-agent" disabled>Single agent (preview only)</option><option value="cole-orchestrator" disabled>Cole orchestrator (not available yet)</option></select></label>
   <label class="check"><input type="checkbox" name="enabled" value="1" checked/>Enabled</label>
   <div><button type="submit" class="btn primary">Save project</button></div>
  </form></section>
 <div class="stack">
  <section class="card" aria-labelledby="ar-h"><h2 id="ar-h">Add a repository</h2>
   <form method="post" action="${bp}/manage" class="stack" style="margin-top:16px">
    <input type="hidden" name="action" value="add-repo"/>
    <label class="field">Project<select name="projectId" required>${options}</select></label>
    <label class="field">GitHub repository<input name="repoRef" required pattern="[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+" placeholder="owner/repo"/></label>
    <div><button type="submit" class="btn">Add repository</button></div>
   </form></section>
  <section class="card stack" id="backfill" aria-labelledby="bf-h"><div class="card-head" style="margin:0"><h2 id="bf-h">GitHub issue backfill</h2><span class="chip off">On demand</span></div>
   <p class="muted small">Reads open issues from enabled GitHub repositories with the package's read-only <code>github</code> credential. Preview never writes. Adding puts eligible issues in the queue as New, in shadow mode: no triage, plan, or agent session starts from here.</p>
   <form class="stack" id="backfill-form" novalidate>
    <div class="form-grid">
     <label class="field">Project<select name="projectId"><option value="">All enabled projects</option>${options}</select></label>
     <label class="field">Issues per repository <small>1–50, newest first</small><input name="perRepoLimit" type="number" min="1" max="50" value="30"/></label>
    </div>
    <div class="row-btns"><button type="submit" class="btn" data-online-only>Preview issues</button><button type="button" class="btn primary" id="backfill-ingest" hidden data-online-only>Add eligible issues</button></div>
    <div id="backfill-result" aria-live="polite"></div>
   </form></section>
  <section class="card stack" id="model" aria-labelledby="mt-h"><div class="card-head" style="margin:0"><h2 id="mt-h">Model triage</h2><span class="chip ${opts.modelAccountSet ? 'on' : 'warn'}">${opts.modelAccountSet ? 'Account configured' : 'Not configured'}</span></div>
   <form method="post" action="${bp}/manage" class="stack">
    <input type="hidden" name="action" value="set-cloudflare-account"/>
    <label class="field">Cloudflare AI account ID <small>${opts.modelAccountSet ? 'Enter a new ID only if you want to change it.' : '32-character account ID.'}</small><input name="cloudflareAccountId" required pattern="[a-f0-9]{32}" autocomplete="off" spellcheck="false"/></label>
    <div><button type="submit" class="btn">Save account ID</button></div>
   </form>
   <form method="post" action="${bp}/manage" class="stack" id="smoke-form" style="border-top:1px solid var(--line);padding-top:16px">
    <input type="hidden" name="action" value="smoke-model"/>
    <div><h3>Check model connection</h3><p class="muted small">Runs one real triage check. No work is created.</p></div>
    <div><button type="submit" class="btn">Check model connection</button></div>
    <div id="smoke-result" aria-live="polite"></div>
   </form></section>
 </div>
 <details class="danger wide"><summary>Delete a project</summary><div class="stack">
  <p class="muted">Removes the project from the factory. Its existing work items stay in the ledger. Disabling is usually the safer choice.</p>
  <form method="post" action="${bp}/manage" class="form-grid">
   <input type="hidden" name="action" value="delete-project"/>
   <label class="field">Project<select name="projectId" required>${options}</select></label>
   <label class="field">Type the project ID to confirm<input name="confirmId" required autocomplete="off" spellcheck="false"/></label>
   <div class="full"><button type="submit" class="btn danger">Delete project</button></div>
  </form></div></details>
</div>`
	return renderShell({ basePath: opts.basePath, view: 'manage', title: 'Manage projects', main })
}