Source index

public/app.js

const $ = selector => document.querySelector(selector);
const state = {local: false, runs: [], selected: null};
function el(tag, text, className) {const element = document.createElement(tag); if (text !== undefined) element.textContent = text; if (className) element.className = className; return element;}
function safeLink(url, label) {const link = el('a', label); if (/^https:\/\/www\.w3\.org\//.test(url)) {link.href = url; link.target = '_blank'; link.rel = 'noopener noreferrer';} return link;}
function renderAnswer(text) {
  const container = $('#answer'); container.replaceChildren();
  for (const paragraph of text.split(/\n\s*\n/)) {
    const node = el('p');
    for (const chunk of paragraph.split(/(https:\/\/www\.w3\.org\/[^\s)\]>]+)/g)) {
      if (chunk.startsWith('https://www.w3.org/')) node.append(safeLink(chunk.replace(/[.,;]+$/, ''), chunk));
      else node.append(document.createTextNode(chunk.replace(/^#{1,4}\s/gm, '').replace(/\*\*/g, '')));
    }
    container.append(node);
  }
}
function renderRun(run) {
  state.selected = run;
  $('#question').value = run.question;
  $('#answer-question').textContent = run.question;
  $('#run-status').textContent = `${state.local && !run.recorded ? 'FRESH LOCAL RUN' : 'RECORDED RUN'} · ${run.status.toUpperCase()}`;
  renderAnswer(run.answer);
  if (run.presentation) $('#answer').prepend(el('p', run.presentation, 'muted'));
  const calls = run.trace.filter(step => step.kind === 'context-tool');
  $('#run-metrics').replaceChildren(el('span', run.model), el('span', `${calls.length} Context calls`), el('span', `${run.usage?.modelCalls || 0} model calls`), el('span', new Date(run.startedAt).toLocaleString()));
  $('#citations').replaceChildren(el('p', 'RETRIEVED W3C SOURCES', 'eyebrow'));
  for (const url of run.citations?.cited || []) {const link = safeLink(url, url.replace('https://www.w3.org/', 'w3.org/')); link.className = 'citation'; $('#citations').append(link);}
  $('#trace').replaceChildren();
  run.trace.forEach((step, index) => {
    const detail = el('details'), summary = el('summary', `${String(index + 1).padStart(2, '0')} · ${step.kind === 'context-tool' ? step.name : 'Local model response'}`);
    detail.append(summary, el('div', step.kind === 'context-tool' ? 'Actual read-only Sanity Context MCP call' : `${step.outputTokens} tokens · ${step.durationMs} ms`, 'trace-kind'));
    const content = step.kind === 'context-tool' ? {origin: step.origin, modelTool: step.modelTool, modelArguments: step.modelArguments, arguments: step.arguments, result: step.result, resultSha256: step.resultSha256} : step.message;
    detail.append(el('pre', JSON.stringify(content, null, 2))); $('#trace').append(detail);
  });
  $('#download-run').disabled = false;
  document.querySelectorAll('.example-button').forEach(button => button.classList.toggle('selected', button.dataset.question === run.question));
}
async function load() {
  try {const response = await fetch('/api/status'); if (response.ok && response.headers.get('content-type')?.includes('application/json')) {const value = await response.json(); state.local = value.mode === 'local-agent';}} catch {}
  if (state.local) {$('#runtime-mode').textContent = 'LOCAL MODEL + LIVE CONTEXT'; $('#mode-note').textContent = 'New questions call your local Qwen model and the live read-only Sanity Context MCP. Saved examples are still labeled recorded.'; $('#ask-button').firstChild.textContent = 'Ask local agent ';}
  try {const response = await fetch('runs/index.json'); if (response.ok) {const manifest = await response.json(); state.runs = await Promise.all(manifest.runs.map(async item => ({...(await (await fetch(`runs/${item.file}`)).json()), label: item.label, recorded: true})));}} catch {}
  $('#examples').replaceChildren();
  if (!state.runs.length) $('#examples').append(el('p', 'Actual saved runs have not been packaged yet.', 'muted'));
  for (const run of state.runs) {const button = el('button', run.label || run.question.slice(0, 35), 'example-button'); button.type = 'button'; button.dataset.question = run.question; button.addEventListener('click', () => {renderRun(run); $('#request-status').textContent = 'Replaying a saved run; no new inference performed.';}); $('#examples').append(button);}
  if (state.runs.length) renderRun(state.runs[0]);
  try {
    const url = new URL('https://2mflxxa8.api.sanity.io/v2026-10-02/data/query/accessatlas');
    url.searchParams.set('query', '{"count":count(*[_type=="guide"]),"guides":*[_type=="guide"]|order(title asc){title,pattern}}'); url.searchParams.set('perspective', 'published');
    const response = await fetch(url); if (!response.ok) throw new Error('Unavailable'); const {result} = await response.json();
    $('#dataset-status').textContent = `CONNECTED · PUBLIC SANITY CONTENT`; $('#dataset-status').classList.add('connected'); $('#guide-count').textContent = result.count;
    if (result.guides.length) $('#coverage-list').replaceChildren(...result.guides.map(guide => el('span', guide.pattern || guide.title)));
  } catch {$('#dataset-status').textContent = 'PUBLIC CONTENT UNAVAILABLE';}
}
$('#question-form').addEventListener('submit', async event => {
  event.preventDefault(); const question = $('#question').value.trim();
  if (!state.local) {
    const recorded = state.runs.find(run => run.question === question);
    if (recorded) {renderRun(recorded); $('#request-status').textContent = 'Replaying a saved run; no new inference performed.';}
    else $('#request-status').textContent = 'Choose a recorded question below. A new question requires the local agent from the source download.';
    return;
  }
  $('#ask-button').disabled = true; $('#request-status').textContent = 'Retrieving real Context MCP content and running local inference…';
  try {const response = await fetch('/api/ask', {method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({question})}); const result = await response.json(); if (!response.ok) throw new Error(result.error); renderRun(result); $('#request-status').textContent = `Fresh local run completed: ${result.status}.`;}
  catch (error) {$('#request-status').textContent = error.message;}
  finally {$('#ask-button').disabled = false;}
});
$('#download-run').addEventListener('click', () => {if (!state.selected) return; const url = URL.createObjectURL(new Blob([JSON.stringify(state.selected, null, 2)], {type: 'application/json'})); const link = el('a'); link.href = url; link.download = 'access-atlas-run.json'; link.click(); URL.revokeObjectURL(url);});
load();