Something went wrong. Try again.
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707import { createHash } from "node:crypto";import { homedir } from "node:os";import { basename, sep } from "node:path";import { getLanguageFromPath } from "@earendil-works/pi-coding-agent";import { Marked } from "@earendil-works/pi-tui";import highlight from "highlight.js";import type { Entry } from "./schema.ts";import type { CatalogueRecord, WorkSnapshot } from "./store.ts";import type { LinkRule } from "../links/contract.ts";import { referenceParts, referenceTarget, type ReferenceContext } from "./references.ts";import type { ViewedFile } from "./files.ts";import type { Transcript } from "./transcript.ts";
const escape = (text: string) => text.replace( /[&<>"']/g, (char) => ({ "&": "&", "<": "<", ">": ">", '"': """, "'": "'" })[char]!, );const anchor = (id: string) => `entry-${id}`;const link = (id: string, label: string) => `<a href="#${encodeURIComponent(id)}">${markdown(label, "link-title", { recordId: "" }, "title")}</a>`;const recordLink = (id: string) => `/records/${encodeURIComponent(id)}`;const sessionLink = (session: string, record: string) => `/sessions/${encodeURIComponent(session)}?${new URLSearchParams({ record })}`;export const MERMAID_PATH = "/mermaid.js";const permalink = (id: string) => `<a class="permalink" href="#${encodeURIComponent(id)}" aria-label="Link to ${escape(id)}">#</a>`;const home = homedir();const tilde = (path: string) => path === home || path.startsWith(home + sep) ? `~${path.slice(home.length)}` : path;const projectList = (projects: string[]) => `<div class="meta">Projects<ul class="projects">${projects.map((project) => `<li><a href="/?${escape(String(new URLSearchParams({ project })))}">${escape(tilde(project))}</a></li>`).join("")}</ul></div>`;const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;// Highlighting is synchronous and blocks Pi, so large files render as plain text.const MAX_HIGHLIGHT_CHARS = 200_000;
const SCRIPT = String.raw`// The viewer cookie admits later requests, so the token need not stay in history.const opened = new URL(location.href);if (opened.searchParams.has('token')) { opened.searchParams.delete('token'); history.replaceState(history.state, '', opened);}const search = document.querySelector('#search');if (search) { const statuses = [...document.querySelectorAll('input[name="status"]')]; const rows = [...document.querySelectorAll('[data-search]')]; const params = new URL(location.href).searchParams; const scopes = [...document.querySelectorAll('[data-param]')].map(list => { const scope = { param: list.dataset.param, values: new Set(params.getAll(list.dataset.param)) }; const input = document.getElementById(scope.param + '-input'); const open = input.form.querySelector('.add-filter'); function render() { list.replaceChildren(...[...scope.values].map(value => { const item = document.createElement('li'); const kind = document.createElement('span'); kind.textContent = scope.param; let label = value; const home = list.dataset.home; if (home && (value === home || value.startsWith(home + '/'))) { label = '~' + value.slice(home.length); } if (scope.param === 'session') { label = document.createElement('a'); label.href = '/sessions/' + encodeURIComponent(value); label.textContent = value; } const remove = document.createElement('button'); remove.type = 'button'; remove.textContent = '\u00d7'; remove.ariaLabel = 'Remove ' + value; remove.addEventListener('click', () => { scope.values.delete(value); render(); filter(); open.focus(); }); item.append(kind, label, remove); return item; })); } function close() { input.value = ''; input.hidden = true; open.hidden = false; } function add() { const value = input.value.trim(); if (value && !scope.values.has(value)) { scope.values.add(value); render(); filter(); } close(); open.focus(); } open.addEventListener('click', () => { open.hidden = true; input.hidden = false; input.focus(); }); input.addEventListener('blur', () => { if (!input.value.trim()) { close(); } }); input.addEventListener('keydown', event => { if (event.key === 'Escape') { close(); open.focus(); } }); input.addEventListener('input', event => { // Datalist choices arrive without typed-text input types. if (!event.inputType || event.inputType === 'insertReplacementText') { add(); } }); // Implicit form submission lets Enter choose an open datalist suggestion first. input.form.addEventListener('submit', event => { event.preventDefault(); add(); }); render(); return scope; }); function filter() { const terms = search.value.toLowerCase().trim().split(/\s+/).filter(Boolean); const selected = statuses.filter(box => box.checked).map(box => box.value); for (const row of rows) { row.hidden = !selected.includes(row.dataset.status) || scopes.some(scope => scope.values.size && !JSON.parse(row.dataset[scope.param]).some(value => scope.values.has(value))) || !terms.every(term => row.dataset.search.includes(term)); } document.querySelector('#no-matches').hidden = rows.some(row => !row.hidden); const url = new URL(location.href); for (const scope of scopes) { url.searchParams.delete(scope.param); for (const value of scope.values) { url.searchParams.append(scope.param, value); } } history.replaceState(history.state, '', url); } search.addEventListener('input', filter); for (const box of statuses) { box.addEventListener('change', filter); } filter();}function anchorTarget() { try { return document.getElementById(decodeURIComponent(location.hash.slice(1))); } catch { return null; }}function reveal() { const target = anchorTarget(); if (!target) { return; } for (let node = target; node; node = node.parentElement) { if (node.tagName === 'DETAILS') { node.open = true; } } if (target.tabIndex < 0) { target.tabIndex = -1; } target.focus({ preventScroll: true }); target.scrollIntoView();}addEventListener('hashchange', reveal);reveal();if (window.mermaid) { mermaid.initialize({ startOnLoad: false, theme: matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'default', suppressErrorRendering: true, }); // Rendering without a container measures diagrams in closed details and keeps the source of a failed diagram. document.querySelectorAll('pre.mermaid').forEach(async (block, i) => { try { block.innerHTML = (await mermaid.render('mermaid-' + i, block.textContent)).svg; } catch { // The block shows its source text. } });}const version = document.body.dataset.version;if (version) { const notice = document.querySelector('#updates'); const timer = setInterval(async () => { if (document.hidden) { return; } try { const response = await fetch(location.pathname, { method: 'HEAD', cache: 'no-store' }); if (!response.ok) { throw new Error(); } if (response.headers.get('etag') !== '"' + version + '"') { notice.hidden = false; notice.textContent = 'Updates available. Reload this page to read them.'; clearInterval(timer); } } catch { notice.hidden = false; notice.textContent = 'Viewer disconnected. Run /work in Pi to reopen it.'; clearInterval(timer); } }, 3000);}`;
const STYLE = `:root { color-scheme: light dark; --bg: #fafafa; --panel: #fff; --text: #252525; --muted: #606060; --line: #d6d6d6; --accent: #1559a6; }@media (prefers-color-scheme: dark) { :root { --bg: #171a20; --panel: #20242c; --text: #e7e9ed; --muted: #b1b7c2; --line: #424955; --accent: #91c5ff; } }* { box-sizing: border-box; }body { background: var(--bg); color: var(--text); font: 16px/1.65 system-ui, sans-serif; margin: auto; max-width: 1000px; padding: 24px; overflow-wrap: anywhere; }a { color: var(--accent); text-underline-offset: 3px; }h1, h2, h3, h4 { line-height: 1.3; }h1 { margin-bottom: 8px; }h2 { font-size: 1.25rem; }h3 { font-size: 1.1rem; }.meta, dt { color: var(--muted); font-size: .9rem; }nav, article, details.section, details.entry { background: var(--panel); border: 1px solid var(--line); border-radius: 8px; margin: 18px 0; padding: 16px 20px; }nav ul { margin: 4px 0; }summary { cursor: pointer; }summary h2, summary h3, summary h4 { display: inline; }summary h3, summary h4 { font-size: 1.1rem; }article { border-radius: 4px; }details.entry:target, article.message:target, article.message:has(span:target), .event:target, .event:has(> span:target) { outline: 2px solid var(--accent); }details.events { margin: -8px 0 0; padding: 0 20px; }details.events > summary { color: var(--muted); font-size: .9rem; }.event { padding: 4px 0; }.event .tools { margin: 0; }.message.user { border-left: 4px solid var(--accent); }.message img { display: block; max-width: 100%; }.tools { margin: 8px 0 0; padding-left: 20px; }.filters { display: grid; gap: 12px; }.filters label { display: inline-flex; align-items: center; gap: 6px; }.filters fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }.scopes { display: flex; flex-wrap: wrap; align-items: center; gap: 8px 16px; }.scopes form { display: flex; flex-wrap: wrap; align-items: center; gap: 6px; }.scopes input[type=text] { width: min(28rem, 80vw); padding: 6px 10px; }.add-filter { font: inherit; font-size: .9rem; color: var(--accent); background: none; border: 1px dashed var(--line); border-radius: 5px; padding: 4px 10px; cursor: pointer; }.tokens { list-style: none; display: flex; flex-wrap: wrap; gap: 6px; margin: 0; padding: 0; }.tokens:empty { display: none; }.tokens li { display: inline-flex; align-items: center; border: 1px solid var(--line); border-radius: 5px; padding: 0.5em; font: .85rem ui-monospace, monospace; }.tokens li span { color: var(--muted); margin-right: 6px; }.tokens button { border: 0; background: none; color: inherit; cursor: pointer; font: inherit; padding: 0 8px; }.filters legend { color: var(--muted); font-size: .9rem; margin-bottom: 4px; }.checks { display: flex; flex-wrap: wrap; gap: 8px 16px; }input[type=checkbox] { accent-color: var(--accent); }.badge { display: inline-block; font-size: .8rem; border: 1px solid var(--line); border-radius: 5px; padding: 0 7px; margin-right: 6px; }.provenance { margin-top: 16px; }.projects { margin: 2px 0 8px; padding-left: 20px; }dl { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 4px 16px; }dd { margin: 0; }pre { overflow-x: auto; background: var(--bg); padding: 16px; border: 1px solid var(--line); border-radius: 4px; }code { font: .9em ui-monospace, monospace; }blockquote { border-left: 3px solid var(--line); margin-left: 0; padding-left: 16px; color: var(--muted); }table { border-collapse: collapse; display: block; overflow-x: auto; }th, td { border: 1px solid var(--line); padding: 6px 12px; text-align: left; }input[type=search], input[type=text] { width: 100%; font: inherit; color: inherit; background: var(--panel); border: 1px solid var(--line); border-radius: 6px; padding: 10px 14px; }#updates { border-left: 3px solid var(--accent); padding: 8px 16px; }.permalink { margin-left: 8px; font-size: .85em; }.file-source { display: grid; grid-template-columns: max-content minmax(0, 1fr); }.file-source pre { margin: 0; border-radius: 0; font: .9em/1.6 ui-monospace, monospace; }.file-source code { font: inherit; }.line-numbers { text-align: right; }.line-numbers a { color: var(--muted); text-decoration: none; }.line-numbers a:target { color: var(--accent); outline: 2px solid var(--accent); }.hljs-keyword, .hljs-selector-tag, .hljs-literal { color: #b13cc5; }.hljs-string, .hljs-regexp, .hljs-attr { color: #2b8651; }.hljs-number, .hljs-built_in, .hljs-type { color: #a96013; }.hljs-title, .hljs-function { color: var(--accent); }.hljs-comment { color: var(--muted); }@media (prefers-color-scheme: dark) { .hljs-keyword, .hljs-selector-tag, .hljs-literal { color: #dfa3f0; } .hljs-string, .hljs-regexp, .hljs-attr { color: #99d6a0; } .hljs-number, .hljs-built_in, .hljs-type { color: #edbe86; } }@media (max-width: 600px) { body { padding: 12px; } nav, article, details.section, details.entry { padding: 12px; } dl { grid-template-columns: 1fr; } }`;
export const CONTENT_POLICY = `default-src 'none'; style-src 'unsafe-inline'; script-src 'self' 'sha256-${createHash("sha256").update(SCRIPT).digest("base64")}'; connect-src 'self'; img-src data:; base-uri 'none'; frame-ancestors 'none'; form-action 'none'`;
function page(title: string, body: string, version = ""): string { return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>${escape(title)}</title><style>${STYLE}</style></head><body data-version="${escape(version)}"><header><a href="/">All work records</a><h1 id="top">${markdown(title, "page-title", { recordId: "" }, "title")}${permalink("top")}</h1></header><p id="updates" role="status" hidden></p><main>${body}</main>${body.includes('<pre class="mermaid">') ? `<script src="${MERMAID_PATH}"></script>` : ""}<script>${SCRIPT}</script></body></html>`;}
function codeHtml(text: string, language?: string): string { if (language && highlight.getLanguage(language)) { try { return highlight.highlight(text, { language, ignoreIllegals: true }).value; } catch { // A grammar failure must not hide the source. } } return escape(text);}
function htmlLink(href: string, label: string): string { return `<a href="${escape(href)}"${href.startsWith("/") || href.startsWith("#") ? "" : ' rel="noreferrer noopener" target="_blank"'}>${label}</a>`;}
function markdown( source: string, prefix: string, context: ReferenceContext, mode: "block" | "inline" | "title" = "block", headingOffset = 3,): string { let heading = 0; let inLink = mode === "title"; const marked = new Marked(); const plain = new marked.Renderer(); marked.use({ renderer: { html({ text }) { return escape(text); }, image({ text }) { return escape(text); }, text(token) { if (inLink || token.type !== "text" || token.tokens || token.escaped) { return false; } const parts = referenceParts(token.text, context); if (!parts.some((part) => part.href)) { return false; } return parts .map((part) => { const label = plain.text({ type: "text", raw: part.text, text: part.text }); return part.href ? htmlLink(part.href, label) : label; }) .join(""); }, codespan({ text }) { const href = inLink ? undefined : referenceTarget(text, context); return href ? `<code>${htmlLink(href, escape(text))}</code>` : false; }, link({ href, tokens }) { const previous = inLink; let label: string; inLink = true; try { label = this.parser.parseInline(tokens); } finally { inLink = previous; } if (mode === "title") { return label; } if (href.startsWith("#")) { return htmlLink(href, label); } try { const url = new URL(href); return ["http:", "https:", "mailto:"].includes(url.protocol) ? htmlLink(url.href, label) : label; } catch { const target = referenceTarget(href, context); return target ? htmlLink(target, label) : label; } }, heading({ tokens, depth }) { const level = Math.min(6, depth + headingOffset); const id = `${prefix}-heading-${heading++}`; return `<h${level} id="${escape(id)}">${this.parser.parseInline(tokens)}${permalink(id)}</h${level}>`; }, code({ text, lang }) { const language = lang?.split(/\s+/)[0]; if (language === "mermaid") { return `<pre class="mermaid">${escape(text)}</pre>`; } return `<pre><code class="hljs">${codeHtml(text, language)}</code></pre>`; }, }, }); return mode === "block" ? marked.parse(source, { async: false }) : marked.parseInline(source, { async: false });}
function provenance(entry: Entry, recordId: string): string { const session = sessionLink(entry.author.session, recordId); const code = (value: string, href?: string) => href ? `<a href="${escape(href)}"><code>${escape(value)}</code></a>` : `<code>${escape(value)}</code>`; const message = (id?: string) => id && code(id, `${session}#${anchor(id)}`); const fields = [ ["Session", code(entry.author.session, session)], ["Message", message(entry.author.entry)], ["Model", entry.author.model && code(entry.author.model)], [ "User message", entry.content.kind === "decision" ? message(entry.content.user_entry) : undefined, ], ]; return `<details class="provenance"><summary>Provenance</summary><dl>${fields .filter(([, value]) => value) .map(([name, value]) => `<dt>${escape(name!)}</dt><dd>${value}</dd>`) .join("")}</dl></details>`;}
function section(id: string, title: string, body: string, count?: number): string { return `<details class="section" id="${id}" open><summary><h2>${escape(title)}${count === undefined ? "" : ` (${count})`}${permalink(id)}</h2></summary>${body}</details>`;}
// Maps each task ID to its subtasks in creation order.function subtaskMap(entries: Entry[]): Map<string, Entry[]> { const tasks = new Set( entries.filter((entry) => entry.content.kind === "task").map((entry) => entry.id), ); const subtasks = new Map<string, Entry[]>(); for (const entry of entries) { const parent = entry.content.kind === "task" ? entry.content.parent : undefined; if (parent && tasks.has(parent)) { subtasks.set(parent, [...(subtasks.get(parent) ?? []), entry]); } } for (const children of subtasks.values()) { children.sort((a, b) => Number(a.id.slice(1)) - Number(b.id.slice(1))); } return subtasks;}
function renderEntry(entry: Entry, context: ReferenceContext, subtasks: Entry[] = []): string { const item = entry.content; if (item.kind === "brief") { return ""; } const id = anchor(entry.id); const sources = item.kind === "task" ? item.evidence : item.sources; const supersedes = item.kind === "task" ? undefined : item.supersedes; const level = item.kind === "decision" ? 3 : 4; return `<details class="entry" id="${escape(id)}"><summary><h${level}>${escape(entry.id)}: ${markdown(item.title, `${id}-title`, context, "inline")}${permalink(id)}</h${level}></summary><p><span class="badge">${escape(item.kind === "decision" ? "decision" : item.status)}</span>${entry.superseded_by ? `Superseded by ${link(anchor(entry.superseded_by), entry.superseded_by)}` : ""}</p><p class="meta">${escape(entry.id)} · revision ${entry.revision} · ${escape(entry.updated)}</p>${supersedes ? `<p>Supersedes ${link(anchor(supersedes), supersedes)}</p>` : ""}${item.kind === "task" && item.blocked_on ? `<p>Blocked on: ${markdown(item.blocked_on, `${id}-blocked-on`, context, "inline")}</p>` : ""}${item.kind === "task" && item.owner ? `<p>Owner: ${escape(item.owner)}</p>` : ""}${markdown(item.body ?? "", id, context, "block", level)}${sources?.length ? `<h${level + 1} id="${id}-sources">${item.kind === "task" ? "Evidence" : "Sources"}${permalink(`${id}-sources`)}</h${level + 1}><ul>${sources.map((source, i) => `<li>${markdown(source, `${id}-source-${i}`, context, "block", level + 1)}</li>`).join("")}</ul>` : ""}${subtasks.map((subtask) => renderEntry(subtask, context)).join("")}${provenance(entry, context.recordId)}</details>`;}
export function renderCatalogue( records: CatalogueRecord[], matchers: LinkRule[] = [], version = "",): string { const sessions = new Map<string, string[]>(); const projects = new Map<string, string[]>(); // Records arrive newest first, so suggestions and their labels start with recent work. for (const record of records) { for (const [values, keys] of [ [sessions, record.sessions.toReversed()], [projects, record.projects], ] as const) { for (const key of keys) { const titles = values.get(key); if (titles) { titles.push(record.title); } else { values.set(key, [record.title]); } } } } const scope = (param: string, placeholder: string, values: Map<string, string[]>) => `<form><ul class="tokens" data-param="${param}"${param === "project" ? ` data-home="${escape(home)}"` : ""} aria-label="${placeholder} filters"></ul><button type="button" class="add-filter">Filter by ${param}</button><input id="${param}-input" type="text" list="${param}-options" placeholder="${placeholder}" aria-label="${placeholder}" autocomplete="off" hidden><datalist id="${param}-options">${[ ...values, ] .map( ([value, titles]) => `<option value="${escape(value)}">${escape(titles[0])}${titles.length > 1 ? ` and ${titles.length - 1} more` : ""}</option>`, ) .join("")}</datalist></form>`; const rows = records .map( (record) => `<article data-status="${escape(record.status)}" data-session="${escape(JSON.stringify(record.sessions))}" data-project="${escape(JSON.stringify(record.projects))}" data-search="${escape([record.title, record.objective, ...record.projects, record.status, record.id].join(" ").toLowerCase())}"><h2><a href="${recordLink(record.id)}">${markdown(record.title, `record-${record.id}-title`, { matchers, recordId: record.id }, "title")}</a></h2><p>${markdown(record.objective, `record-${record.id}-objective`, { matchers, recordId: record.id }, "inline")}</p><p><span class="badge">${escape(record.status)}</span><span class="meta">revision ${record.revision} · ${escape(record.updated)}</span></p>${projectList(record.projects)}<p class="meta"><code>${escape(record.id)}</code></p></article>`, ) .join(""); return page( "Work records", `<div class="filters"><div><label for="search">Search titles, objectives, projects, status, or record IDs</label><input id="search" type="search" placeholder="Filter records" autocomplete="off"></div><div class="scopes">${scope("session", "Session ID", sessions)}${scope("project", "Project path", projects)}</div><fieldset><legend>Status</legend><div class="checks">${(["active", "blocked", "complete", "archived"] as const).map((status) => `<label><input type="checkbox" name="status" value="${status}"${status === "active" || status === "blocked" ? " checked" : ""}>${status.charAt(0).toUpperCase() + status.slice(1)}</label>`).join("")}</div></fieldset></div><p class="meta">${records.length} records</p>${rows}<p id="no-matches" ${records.length ? "hidden" : ""}>No matching records. Check more statuses or remove session and project filters.</p>`, version, );}
export function groupRecordEntries(allEntries: Entry[]) { const subtasks = new Set([...subtaskMap(allEntries).values()].flat()); return ( [ ["tasks", "Tasks", "task"], ["findings", "Findings", "finding"], ["decisions", "Decisions", "decision"], ] as const ).map(([id, title, kind]) => { const entries = allEntries.filter((entry) => entry.content.kind === kind); const current = entries.filter((entry) => !entry.superseded_by && !subtasks.has(entry)); const states = kind === "task" ? ["pending", "active", "blocked", "done", "cancelled"] : kind === "finding" ? ["confirmed", "hypothesis", "refuted"] : ["current"]; const groups = states .map((state) => ({ id: `${id}-${state}`, title: state === "current" ? "" : state.charAt(0).toUpperCase() + state.slice(1), entries: current.filter( (entry) => entry.content.kind === "decision" || ((entry.content.kind === "task" || entry.content.kind === "finding") && entry.content.status === state), ), collapsed: false, })) .filter((group) => group.entries.length); const superseded = entries.filter((entry) => entry.superseded_by); if (superseded.length) { groups.push({ id: `${id}-superseded`, title: "Superseded", entries: superseded, collapsed: true, }); } return { id, title, entries, groups }; });}
export function renderRecord(snapshot: WorkSnapshot, matchers: LinkRule[] = []): string { const context = { matchers, recordId: snapshot.id }; const briefEntry = snapshot.entries.find((entry) => entry.id === "brief"); if (briefEntry?.content.kind !== "brief") { throw new Error("Invalid work report brief"); } const brief = briefEntry.content; const sections = groupRecordEntries(snapshot.entries); const subtasks = subtaskMap(snapshot.entries); const contentsItem = (entry: Entry): string => `<li>${link(anchor(entry.id), `${entry.id}: ${entry.content.title}${entry.superseded_by ? " (superseded)" : ""}`)}${subtasks.has(entry.id) ? `<ul>${subtasks.get(entry.id)?.map(contentsItem).join("")}</ul>` : ""}</li>`; const contents = `<nav aria-label="Contents"><details id="contents" open><summary><h2>Contents${permalink("contents")}</h2></summary><ul><li>${link("brief", "Brief")}</li>${sections .map( ({ id, title, groups }) => `<li>${link(id, title)}<ul>${groups .map((group) => { const items = group.entries.map(contentsItem).join(""); return group.title ? `<li>${link(group.id, `${group.title} (${group.entries.length})`)}<ul>${items}</ul></li>` : items; }) .join("")}</ul></li>`, ) .join("")}</ul></details></nav>`; const sessions = new Map<string, string>(); for (const entry of snapshot.entries.toReversed()) { if (!sessions.has(entry.author.session)) { sessions.set(entry.author.session, entry.updated); } } const sessionList = `<div class="meta">Session transcripts<ul class="projects">${[...sessions] .map( ([session, updated]) => `<li><a href="${escape(sessionLink(session, snapshot.id))}"><code>${escape(session)}</code></a> · ${escape(updated)}</li>`, ) .join("")}</ul></div>`; const summary = `<p><span class="badge">${escape(brief.status)}</span><span class="meta">Snapshot revision ${snapshot.revision}</span></p><p class="meta"><code>${escape(snapshot.id)}</code></p>${projectList(brief.projects)}${sessionList}`; const fields = [ ["objective", "Objective"], ["scope", "Scope"], ["constraints", "Constraints"], ["approach", "Approach"], ] as const; const overview = fields .filter(([key]) => brief[key]) .map( ([key, title]) => `<h3 id="brief-${key}">${title}${permalink(`brief-${key}`)}</h3>${markdown(brief[key] ?? "", `brief-${key}`, context)}`, ) .join(""); const related = brief.related?.length ? `<h3 id="related">Related records${permalink("related")}</h3><ul>${brief.related.map((value, i) => `<li>${uuid.test(value) ? `<a href="${recordLink(value)}">${escape(value)}</a>` : markdown(value, `related-${i}`, context, "inline")}</li>`).join("")}</ul>` : ""; const body = sections .map(({ id, title, entries, groups }) => section( id, title, groups .map((group) => { const body = group.entries .map((entry) => renderEntry(entry, context, subtasks.get(entry.id))) .join(""); if (!group.title) { return body; } const heading = `<h3>${escape(group.title)} (${group.entries.length})${permalink(group.id)}</h3>`; return group.collapsed ? `<details id="${group.id}"><summary>${heading}</summary>${body}</details>` : `<section id="${group.id}">${heading}${body}</section>`; }) .join("") || "<p>No entries.</p>", entries.length, ), ) .join(""); return page( brief.title, `${summary}${contents}${section("brief", "Brief", `<p class="meta">Revision ${briefEntry.revision} · ${escape(briefEntry.updated)}</p>` + overview + related + provenance(briefEntry, snapshot.id))}${body}`, String(snapshot.revision), );}
export function renderFile(file: ViewedFile, recordId: string): string { const numbers = file.text .split("\n") .map((_, i) => `<a id="L${i + 1}" href="#L${i + 1}">${i + 1}</a>`) .join("\n"); return page( basename(file.path), `<p><a href="${recordLink(recordId)}">Back to work record</a></p><p class="meta">Current file contents</p><p><code>${escape(file.path)}</code></p><div class="file-source"><pre class="line-numbers" aria-label="Line numbers">${numbers}</pre><pre><code class="hljs">${codeHtml(file.text, file.text.length > MAX_HIGHLIGHT_CHARS ? undefined : getLanguageFromPath(file.path))}</code></pre></div>`, );}
export function renderTranscript( transcript: Transcript, matchers: LinkRule[], recordId: string,): string { const context = { matchers, recordId }; const anchors = (ids: string[]) => ids.map((id) => `<span id="${escape(anchor(id))}"></span>`).join(""); const items: string[] = []; let events: string[] = []; let calls = 0; let others = 0; const plural = (count: number, noun: string) => `${count} ${noun}${count === 1 ? "" : "s"}`; const flush = () => { if (events.length) { const label = [ calls ? `Made ${plural(calls, "tool call")}` : "", others ? plural(others, calls ? "other event" : "event") : "", ]; items.push( `<details class="events"><summary>${label.filter(Boolean).join(" and ")}</summary>${events.join("")}</details>`, ); } events = []; calls = 0; others = 0; }; for (const item of transcript.items) { const id = anchor(item.id); const text = `${item.text ? markdown(item.text, id, context) : ""}${(item.images ?? []).map((src) => `<img src="${escape(src)}" alt="">`).join("")}`; const tools = item.tools.length ? `<ul class="tools">${item.tools.map((tool) => `<li><code>${escape(tool)}</code></li>`).join("")}</ul>` : ""; const message = item.kind === "user" || (item.kind === "assistant" && item.text.trim() !== "") || Boolean(item.images?.length); if (message || item.branch) { flush(); } if (item.branch) { items.push(`<p class="meta">Branch from ${link(anchor(item.branch), item.branch)}</p>`); } const meta = `<p class="meta">${escape(item.label)} · ${escape(item.timestamp)}${permalink(id)}</p>`; if (item.kind === "assistant") { calls += item.tools.length; } else if (!message) { others += 1; } if (message) { items.push( `<article class="message ${item.kind}" id="${escape(id)}">${meta}${text}${anchors(item.anchors)}</article>`, ); if (tools) { events.push(tools); } continue; } events.push( `<div class="event" id="${escape(id)}">${meta}${item.kind === "summary" ? `<details><summary>Show summary</summary>${text}</details>` : text}${tools}${anchors(item.anchors)}</div>`, ); } flush(); return page( transcript.name ?? "Session transcript", `${recordId ? `<p><a href="${recordLink(recordId)}">Back to work record</a></p>` : ""}<p class="meta"><code>${escape(transcript.id)}</code>${transcript.cwd ? ` · <code>${escape(tilde(transcript.cwd))}</code>` : ""}</p>${anchors(transcript.anchors)}${items.join("") || "<p>No messages.</p>"}`, );}
export function renderError(message: string): string { return page("Work viewer", `<p>${escape(message)}</p>`);}