arnaucube
arnaucube/study-labPublic Self-hosted repository
study-lab/app.js
app.jsRaw
   1(() => {
   2  'use strict';
   3
   4  const APP_PREFIX = 'study-lab';
   5  const STORAGE_KEY = `${APP_PREFIX}:v1`;
   6  const SETTINGS_KEY = `${APP_PREFIX}:settings:v1`;
   7  const USAGE_KEY = `${APP_PREFIX}:usage:v1`;
   8  const OPENROUTER_PRICES_KEY = `${APP_PREFIX}:openrouter-prices:v1`;
   9  const TREE_ZOOM_KEY = `${APP_PREFIX}:tree-zoom`;
  10  const THEME_KEY = `${APP_PREFIX}:theme`;
  11  const PDF_REQUEST_LIMIT = 50 * 1024 * 1024;
  12  const PRICE_CACHE_TTL = 24 * 60 * 60 * 1000;
  13  const PROVIDERS = {
  14    openai: {
  15      label: 'OpenAI', apiUrl: 'https://api.openai.com/v1/responses', model: 'gpt-5-mini',
  16      models: ['gpt-5-mini', 'gpt-5', 'gpt-4.1-mini', 'gpt-4.1']
  17    },
  18    openrouter: {
  19      label: 'OpenRouter', apiUrl: 'https://openrouter.ai/api/v1/responses', model: 'openai/gpt-5-mini',
  20      models: ['openai/gpt-5-mini', 'anthropic/claude-sonnet-4', 'google/gemini-2.5-pro', 'deepseek/deepseek-r1']
  21    }
  22  };
  23  // USD per million tokens. Last checked against OpenAI Docs on 2026-08-17.
  24  const MODEL_PRICES = [
  25    { match: /^gpt-5\.6-terra(?:-|$)/, input: 2, cached: .2, output: 12 },
  26    { match: /^gpt-5\.6-luna(?:-|$)/, input: .2, cached: .02, output: 1.2 },
  27    { match: /^gpt-5\.6-sol(?:-|$)/, input: 5, cached: .5, output: 30 },
  28    { match: /^gpt-5\.6$/, input: 5, cached: .5, output: 30 },
  29    { match: /^gpt-5\.4-mini(?:-|$)/, input: .75, cached: .075, output: 4.5 },
  30    { match: /^gpt-5\.4(?:-20\d{2}|$)/, input: 2.5, cached: .25, output: 15 },
  31    { match: /^gpt-5-mini(?:-|$)/, input: .25, cached: .025, output: 2 },
  32    { match: /^gpt-5-nano(?:-|$)/, input: .05, cached: .005, output: .4 },
  33    { match: /^gpt-5(?:-20\d{2}|$)/, input: 1.25, cached: .125, output: 10 },
  34    { match: /^gpt-4\.1-mini(?:-|$)/, input: .4, cached: .1, output: 1.6 },
  35    { match: /^gpt-4\.1(?:-20\d{2}|$)/, input: 2, cached: .5, output: 8 },
  36    { match: /^gpt-4o-mini(?:-|$)/, input: .15, cached: .075, output: .6 }
  37  ];
  38  const DEFAULT_SETTINGS = {
  39    provider: 'openai',
  40    apiKey: '',
  41    model: 'gpt-5-mini',
  42    apiUrl: 'https://api.openai.com/v1/responses',
  43    profiles: {
  44      openai: { apiKey: '', model: 'gpt-5-mini', apiUrl: 'https://api.openai.com/v1/responses' },
  45      openrouter: { apiKey: '', model: 'openai/gpt-5-mini', apiUrl: 'https://openrouter.ai/api/v1/responses' }
  46    },
  47    systemPrompt: 'You are a patient technical tutor. Use clear Markdown and LaTeX where useful. Use mathematical language, assume graduate level knowledge. Build on the conversation context and explain assumptions.'
  48  };
  49
  50  const $ = (selector, root = document) => root.querySelector(selector);
  51  const els = {
  52    welcome: $('#welcome'), conversation: $('#conversation'), composer: $('#composer'),
  53    prompt: $('#prompt'), send: $('#send'), tree: $('#tree'), mapEmpty: $('#map-empty'),
  54    nodeCount: $('#node-count'), branchCount: $('#branch-count'), branchContext: $('#branch-context'),
  55    branchLabel: $('#branch-label'), selectionMenu: $('#selection-menu'), selectionPreview: $('#selection-preview'),
  56    selectionAction: $('#selection-action'), selectionCustom: $('#selection-custom'), settings: $('#settings-dialog'),
  57    provider: $('#provider'), openaiApiKey: $('#openai-api-key'), openrouterApiKey: $('#openrouter-api-key'),
  58    openaiModel: $('#openai-model'), openrouterModel: $('#openrouter-model'),
  59    openaiModelOptions: $('#openai-model-options'), openrouterModelOptions: $('#openrouter-model-options'),
  60    openaiApiUrl: $('#openai-api-url'), openrouterApiUrl: $('#openrouter-api-url'), systemPrompt: $('#system-prompt'),
  61    keyStatus: $('#key-status'), toast: $('#toast'), usageDialog: $('#usage-dialog'),
  62    monthTokens: $('#month-tokens'), usageMonth: $('#usage-month'), usageTotal: $('#usage-total'),
  63    usageCost: $('#usage-cost'), usageRequests: $('#usage-requests'), usageInput: $('#usage-input'),
  64    usageCached: $('#usage-cached'), usageOutput: $('#usage-output'), usageModels: $('#usage-models'),
  65    usageRecent: $('#usage-recent'), usageNote: $('#usage-note'), usageDashboard: $('#usage-dashboard'), historyList: $('#history-list'),
  66    historyEmpty: $('#history-empty'), historyToggle: $('#toggle-history'),
  67    attachments: $('#attachments'), uploadPDF: $('#upload-pdf'), pdfInput: $('#pdf-input'),
  68    activeConnection: $('#active-connection'), activeModel: $('#active-model'), activeProvider: $('#active-provider'),
  69    conversationSearch: $('#conversation-search'), searchResults: $('#search-results'),
  70    treeZoom: $('#tree-zoom'), shortcutsDialog: $('#shortcuts-dialog')
  71  };
  72
  73  migrateLegacyStorage();
  74  let settings = normalizeSettings(loadJSON(SETTINGS_KEY, DEFAULT_SETTINGS));
  75  let settingsDraftProfiles = null;
  76  let workspace = loadWorkspace();
  77  let state = currentMap();
  78  let usageRecords = loadUsage();
  79  let openRouterPrices = loadOpenRouterPrices();
  80  let activeRequest = null;
  81  let uploadingPDFs = false;
  82  let uploadTargetMapId = null;
  83  let selectedText = null;
  84  let saveTimer = 0;
  85  let toastTimer = 0;
  86  let searchTimer = 0;
  87  let searchIndex = null;
  88  let pendingG = false;
  89  let pendingGTimer = 0;
  90  let treeZoom = loadTreeZoom();
  91
  92  function loadJSON(key, fallback) {
  93    try { return JSON.parse(localStorage.getItem(key) || 'null') || fallback; }
  94    catch { return { ...fallback }; }
  95  }
  96
  97  function normalizeSettings(value = {}) {
  98    const provider = PROVIDERS[value.provider] ? value.provider : 'openai';
  99    const profiles = {};
 100    for (const [id, defaults] of Object.entries(PROVIDERS)) {
 101      const saved = value.profiles?.[id] || {};
 102      profiles[id] = {
 103        apiKey: String(saved.apiKey || ''),
 104        model: String(saved.model || defaults.model),
 105        apiUrl: String(saved.apiUrl || defaults.apiUrl)
 106      };
 107    }
 108    // Settings saved before providers were introduced belong to OpenAI.
 109    if (!value.profiles) {
 110      profiles.openai = {
 111        apiKey: String(value.apiKey || ''),
 112        model: String(value.model || PROVIDERS.openai.model),
 113        apiUrl: String(value.apiUrl || PROVIDERS.openai.apiUrl)
 114      };
 115    }
 116    const active = profiles[provider];
 117    return {
 118      provider, profiles, apiKey: active.apiKey, model: active.model, apiUrl: active.apiUrl,
 119      systemPrompt: String(value.systemPrompt ?? DEFAULT_SETTINGS.systemPrompt)
 120    };
 121  }
 122
 123  function providerLabel(provider = settings.provider) {
 124    return PROVIDERS[provider]?.label || 'API provider';
 125  }
 126
 127  function requestHeaders(json = false, connection = settings) {
 128    const headers = { 'Authorization': `Bearer ${connection.apiKey}` };
 129    if (json) headers['Content-Type'] = 'application/json';
 130    if (connection.provider === 'openrouter') headers['X-OpenRouter-Title'] = 'Study Lab';
 131    return headers;
 132  }
 133
 134  function migrateLegacyStorage() {
 135    const legacyPrefix = ['study', 'pal'].join('-');
 136    const suffixes = [':v1', ':settings:v1', ':usage:v1', ':theme', ':tree-zoom'];
 137    for (const suffix of suffixes) {
 138      const currentKey = `${APP_PREFIX}${suffix}`;
 139      const legacyKey = `${legacyPrefix}${suffix}`;
 140      try {
 141        if (localStorage.getItem(currentKey) === null && localStorage.getItem(legacyKey) !== null) {
 142          localStorage.setItem(currentKey, localStorage.getItem(legacyKey));
 143        }
 144      } catch {}
 145    }
 146  }
 147
 148  function loadUsage() {
 149    try {
 150      const records = JSON.parse(localStorage.getItem(USAGE_KEY) || '[]');
 151      return Array.isArray(records) ? records.filter(record => record && Number.isFinite(record.timestamp)) : [];
 152    } catch { return []; }
 153  }
 154
 155  function loadOpenRouterPrices() {
 156    try {
 157      const prices = JSON.parse(localStorage.getItem(OPENROUTER_PRICES_KEY) || '{}');
 158      return prices && typeof prices === 'object' && !Array.isArray(prices) ? prices : {};
 159    } catch { return {}; }
 160  }
 161
 162  function persistOpenRouterPrices() {
 163    const recent = Object.entries(openRouterPrices)
 164      .sort((a, b) => (Number(b[1]?.checkedAt) || 0) - (Number(a[1]?.checkedAt) || 0))
 165      .slice(0, 40);
 166    openRouterPrices = Object.fromEntries(recent);
 167    try { localStorage.setItem(OPENROUTER_PRICES_KEY, JSON.stringify(openRouterPrices)); } catch {}
 168  }
 169
 170  function loadTreeZoom() {
 171    try { return Math.max(.8, Math.min(1.4, Number(localStorage.getItem(TREE_ZOOM_KEY)) || 1)); }
 172    catch { return 1; }
 173  }
 174
 175  function blankMap() {
 176    const now = Date.now();
 177    return { id: uid(), title: 'Untitled map', titleCustom: false, nodes: [], attachments: [], collapsedIds: [], activeId: null, createdAt: now, updatedAt: now };
 178  }
 179
 180  function titleFromNodes(nodes) {
 181    const first = nodes.find(node => !node.parentId) || nodes[0];
 182    if (!first) return 'Untitled map';
 183    const title = String(first.question).replace(/\s+/g, ' ').trim();
 184    return title.length > 54 ? `${title.slice(0, 54)}…` : title;
 185  }
 186
 187  function normalizeMap(value = {}) {
 188    const normalized = normalizeState(value);
 189    const attachments = Array.isArray(value.attachments) ? value.attachments
 190      .filter(file => file && file.id && file.name)
 191      .map(file => ({
 192        id: String(file.id), name: String(file.name), size: Number(file.size) || 0,
 193        createdAt: Number(file.createdAt) || Date.now(), detail: file.detail === 'high' ? 'high' : 'low',
 194        provider: PROVIDERS[file.provider] ? file.provider : 'openai'
 195      })) : [];
 196    const createdAt = Number(value.createdAt) || Number(normalized.nodes[0]?.createdAt) || Date.now();
 197    return {
 198      id: String(value.id || uid()),
 199      title: String(value.title || titleFromNodes(normalized.nodes)),
 200      titleCustom: Boolean(value.titleCustom),
 201      ...normalized,
 202      attachments,
 203      collapsedIds: Array.isArray(value.collapsedIds) ? [...new Set(value.collapsedIds.map(String))] : [],
 204      createdAt,
 205      updatedAt: Number(value.updatedAt) || Number(normalized.nodes.at(-1)?.createdAt) || createdAt
 206    };
 207  }
 208
 209  function loadWorkspace() {
 210    let raw = null;
 211    try { raw = JSON.parse(localStorage.getItem(STORAGE_KEY) || 'null'); } catch {}
 212    let maps = [];
 213    let activeMapId = null;
 214    if (raw && Array.isArray(raw.maps)) {
 215      maps = raw.maps.filter(Boolean).map(normalizeMap);
 216      activeMapId = raw.activeMapId;
 217    } else if (raw && Array.isArray(raw.nodes) && raw.nodes.length) {
 218      // Migrate the original single-map schema in place.
 219      const migrated = normalizeMap(raw);
 220      maps = [migrated];
 221      activeMapId = migrated.id;
 222    }
 223    if (!maps.length) maps.push(blankMap());
 224    if (!maps.some(map => map.id === activeMapId)) activeMapId = maps[0].id;
 225    return { version: 2, maps, activeMapId };
 226  }
 227
 228  function currentMap() {
 229    return workspace.maps.find(map => map.id === workspace.activeMapId) || workspace.maps[0];
 230  }
 231
 232  function normalizeState(value) {
 233    const nodes = Array.isArray(value.nodes) ? value.nodes.filter(n => n && n.id && n.question).map(node => {
 234      if (node.status !== 'loading') return node;
 235      return { ...node, status: 'error', error: 'The page was closed before this response finished.' };
 236    }) : [];
 237    const activeId = nodes.some(n => n.id === value.activeId) ? value.activeId : (nodes.at(-1)?.id || null);
 238    return { nodes, activeId };
 239  }
 240
 241  function persistSoon() {
 242    clearTimeout(saveTimer);
 243    saveTimer = setTimeout(() => {
 244      try { localStorage.setItem(STORAGE_KEY, JSON.stringify(workspace)); }
 245      catch { showToast('Browser storage is full — conversations could not be saved'); }
 246    }, 180);
 247  }
 248
 249  function persistNow() {
 250    clearTimeout(saveTimer);
 251    try { localStorage.setItem(STORAGE_KEY, JSON.stringify(workspace)); return true; }
 252    catch { showToast('Browser storage is full — conversations could not be saved'); return false; }
 253  }
 254
 255  function touchMap(map = state) { map.updatedAt = Date.now(); searchIndex = null; }
 256
 257  function refreshMapTitle(map = state) {
 258    if (!map.titleCustom) map.title = titleFromNodes(map.nodes);
 259  }
 260
 261  function nodeById(id, map = state) { return map.nodes.find(node => node.id === id); }
 262
 263  function pathTo(id, map = state) {
 264    const path = [];
 265    const seen = new Set();
 266    let node = nodeById(id, map);
 267    while (node && !seen.has(node.id)) {
 268      seen.add(node.id);
 269      path.push(node);
 270      node = nodeById(node.parentId, map);
 271    }
 272    return path.reverse();
 273  }
 274
 275  function childrenOf(id) { return state.nodes.filter(node => node.parentId === id); }
 276
 277  function uid() {
 278    return globalThis.crypto?.randomUUID?.() || `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
 279  }
 280
 281  function escapeHTML(value = '') {
 282    return value.replace(/[&<>'"]/g, char => ({ '&':'&amp;', '<':'&lt;', '>':'&gt;', "'":'&#39;', '"':'&quot;' })[char]);
 283  }
 284
 285  function inlineMarkdown(text) {
 286    let output = escapeHTML(text);
 287    output = output.replace(/`([^`]+)`/g, '<code>$1</code>');
 288    output = output.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>');
 289    output = output.replace(/(?<!\*)\*([^*\n]+)\*(?!\*)/g, '<em>$1</em>');
 290    output = output.replace(/\[([^\]]+)\]\((https?:\/\/[^\s)]+)\)/g, '<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>');
 291    return output;
 292  }
 293
 294  function tableCells(line) {
 295    let source = line.trim();
 296    if (source.startsWith('|')) source = source.slice(1);
 297    if (source.endsWith('|') && !source.endsWith('\\|')) source = source.slice(0, -1);
 298    const cells = [];
 299    let cell = '';
 300    let code = false;
 301    for (let index = 0; index < source.length; index += 1) {
 302      const char = source[index];
 303      if (char === '\\' && source[index + 1] === '|') {
 304        cell += '|';
 305        index += 1;
 306      } else if (char === '`') {
 307        code = !code;
 308        cell += char;
 309      } else if (char === '|' && !code) {
 310        cells.push(cell.trim());
 311        cell = '';
 312      } else cell += char;
 313    }
 314    cells.push(cell.trim());
 315    return cells;
 316  }
 317
 318  function tableDelimiter(line) {
 319    const cells = tableCells(line);
 320    if (!line.includes('|') || !cells.length || cells.some(cell => !/^:?-{3,}:?$/.test(cell))) return null;
 321    return cells.map(cell => cell.startsWith(':') && cell.endsWith(':') ? 'center' : cell.endsWith(':') ? 'right' : cell.startsWith(':') ? 'left' : '');
 322  }
 323
 324  function renderTable(header, alignments, rows) {
 325    const cellHTML = (cell, tag, index) => {
 326      const alignment = alignments[index] ? ` style="text-align: ${alignments[index]}"` : '';
 327      const scope = tag === 'th' ? ' scope="col"' : '';
 328      return `<${tag}${scope}${alignment}>${inlineMarkdown(cell || '')}</${tag}>`;
 329    };
 330    const head = header.map((cell, index) => cellHTML(cell, 'th', index)).join('');
 331    const body = rows.map(row => `<tr>${header.map((_, index) => cellHTML(row[index], 'td', index)).join('')}</tr>`).join('');
 332    return `<div class="table-scroll"><table><thead><tr>${head}</tr></thead>${body ? `<tbody>${body}</tbody>` : ''}</table></div>`;
 333  }
 334
 335  function renderMath(source, displayMode) {
 336    if (!globalThis.katex) return `<code class="math-fallback">${escapeHTML(source)}</code>`;
 337    try { return katex.renderToString(source, { displayMode, throwOnError: false, strict: false, trust: false }); }
 338    catch { return `<code class="math-fallback">${escapeHTML(source)}</code>`; }
 339  }
 340
 341  function markdown(source = '') {
 342    const stash = [];
 343    const token = html => `\u0000${stash.push(html) - 1}\u0000`;
 344    let text = source.replace(/\r\n?/g, '\n');
 345    text = text.replace(/```([\w+-]*)\n([\s\S]*?)```/g, (_, lang, code) => token(`<pre data-language="${escapeHTML(lang)}"><code>${escapeHTML(code.trimEnd())}</code></pre>`));
 346    text = text.replace(/\$\$([\s\S]*?)\$\$/g, (_, formula) => token(renderMath(formula.trim(), true)));
 347    text = text.replace(/\\\[([\s\S]*?)\\\]/g, (_, formula) => token(renderMath(formula.trim(), true)));
 348    text = text.replace(/\\\((.*?)\\\)/g, (_, formula) => token(renderMath(formula.trim(), false)));
 349    text = text.replace(/(?<!\\)\$([^$\n]+?)\$/g, (_, formula) => token(renderMath(formula.trim(), false)));
 350
 351    const lines = text.split('\n');
 352    const html = [];
 353    let paragraph = [];
 354    let list = null;
 355    const flushParagraph = () => {
 356      if (paragraph.length) html.push(`<p>${inlineMarkdown(paragraph.join('\n')).replace(/\n/g, '<br>')}</p>`);
 357      paragraph = [];
 358    };
 359    const closeList = () => { if (list) html.push(`</${list}>`); list = null; };
 360
 361    for (let lineIndex = 0; lineIndex < lines.length; lineIndex += 1) {
 362      const line = lines[lineIndex];
 363      const alignments = lineIndex + 1 < lines.length ? tableDelimiter(lines[lineIndex + 1]) : null;
 364      if (alignments) {
 365        const header = tableCells(line);
 366        if (header.length === alignments.length) {
 367          flushParagraph(); closeList();
 368          const rows = [];
 369          lineIndex += 2;
 370          while (lineIndex < lines.length && lines[lineIndex].trim() && lines[lineIndex].includes('|')) {
 371            rows.push(tableCells(lines[lineIndex]));
 372            lineIndex += 1;
 373          }
 374          html.push(renderTable(header, alignments, rows));
 375          lineIndex -= 1;
 376          continue;
 377        }
 378      }
 379      const heading = line.match(/^(#{1,3})\s+(.+)/);
 380      const bullet = line.match(/^\s*[-*+]\s+(.+)/);
 381      const numbered = line.match(/^\s*\d+[.)]\s+(.+)/);
 382      const quote = line.match(/^>\s?(.*)/);
 383      const blockToken = line.match(/^\u0000(\d+)\u0000$/);
 384      if (blockToken) { flushParagraph(); closeList(); html.push(stash[Number(blockToken[1])]); }
 385      else if (heading) { flushParagraph(); closeList(); const level = heading[1].length; html.push(`<h${level}>${inlineMarkdown(heading[2])}</h${level}>`); }
 386      else if (bullet || numbered) {
 387        flushParagraph();
 388        const wanted = bullet ? 'ul' : 'ol';
 389        if (list !== wanted) { closeList(); html.push(`<${wanted}>`); list = wanted; }
 390        html.push(`<li>${inlineMarkdown((bullet || numbered)[1])}</li>`);
 391      } else if (quote) { flushParagraph(); closeList(); html.push(`<blockquote>${inlineMarkdown(quote[1])}</blockquote>`); }
 392      else if (!line.trim()) { flushParagraph(); closeList(); }
 393      else paragraph.push(line);
 394    }
 395    flushParagraph(); closeList();
 396    return html.join('').replace(/\u0000(\d+)\u0000/g, (_, index) => stash[Number(index)]);
 397  }
 398
 399  function answerHTML(node) {
 400    if (node.status === 'loading' && !node.answer) return '<span class="thinking" aria-label="Thinking"><i></i><i></i><i></i></span>';
 401    if (node.status === 'error') return `<p class="error-text">${escapeHTML(node.error || 'The request failed.')}</p>`;
 402    return markdown(node.answer || '');
 403  }
 404
 405  function answerAttribution(node) {
 406    if (!node.model || !node.provider || !node.answer) return '';
 407    return `<div class="answer-attribution" title="Generated by ${escapeHTML(node.model)} through ${escapeHTML(providerLabel(node.provider))}"><span>${escapeHTML(node.model)}</span><small>${escapeHTML(providerLabel(node.provider))}</small></div>`;
 408  }
 409
 410  function renderConversation({ scroll = false } = {}) {
 411    const previousScroll = scroll ? null : { left: window.scrollX, top: window.scrollY };
 412    const path = pathTo(state.activeId);
 413    els.welcome.hidden = path.length > 0;
 414    els.conversation.hidden = path.length === 0;
 415    const fragment = document.createDocumentFragment();
 416    for (const node of path) {
 417      const article = document.createElement('article');
 418      article.className = 'message';
 419      article.dataset.nodeId = node.id;
 420      article.innerHTML = `
 421        <div class="question-row"><div class="question-bubble">${escapeHTML(node.question)}</div></div>
 422        <div class="answer"><span class="answer-mark" aria-hidden="true">S</span><div class="answer-content"><div class="answer-body">${answerHTML(node)}</div>${answerAttribution(node)}</div></div>
 423        <div class="answer-actions">
 424          <button class="mini-action copy-answer" type="button">Copy answer</button>
 425          <button class="mini-action branch-here" type="button">Branch here</button>
 426          ${node.status === 'error' ? '<button class="mini-action retry-node" type="button">Retry</button>' : ''}
 427        </div>`;
 428      fragment.append(article);
 429    }
 430    els.conversation.replaceChildren(fragment);
 431    if (previousScroll && (window.scrollX !== previousScroll.left || window.scrollY !== previousScroll.top)) {
 432      window.scrollTo({ ...previousScroll, behavior: 'auto' });
 433    }
 434    renderBranchContext();
 435    if (scroll && state.activeId) requestAnimationFrame(() => {
 436      if (scroll === 'bottom') {
 437        window.scrollTo({ top: document.documentElement.scrollHeight, behavior: 'smooth' });
 438        return;
 439      }
 440      const targetId = state.activeId;
 441      requestAnimationFrame(() => {
 442        if (state.activeId !== targetId) return;
 443        const message = $(`.message[data-node-id="${CSS.escape(targetId)}"]`, els.conversation);
 444        if (!message) return;
 445        const headerHeight = $('.topbar')?.getBoundingClientRect().height || 68;
 446        const top = window.scrollY + message.getBoundingClientRect().top - headerHeight - 14;
 447        window.scrollTo({ top: Math.max(0, top), behavior: 'smooth' });
 448      });
 449    });
 450  }
 451
 452  function renderTree() {
 453    const ids = new Set(state.nodes.map(node => node.id));
 454    const grouped = new Map();
 455    for (const node of state.nodes) {
 456      const parentId = node.parentId && ids.has(node.parentId) ? node.parentId : null;
 457      if (!grouped.has(parentId)) grouped.set(parentId, []);
 458      grouped.get(parentId).push(node);
 459    }
 460    const roots = grouped.get(null) || [];
 461    const activePath = new Set(pathTo(state.activeId).map(node => node.id));
 462    const collapsed = new Set(state.collapsedIds);
 463    const build = nodes => {
 464      const ul = document.createElement('ul');
 465      for (const node of nodes) {
 466        const li = document.createElement('li');
 467        li.dataset.nodeId = node.id;
 468        const wrap = document.createElement('div');
 469        wrap.className = 'tree-node-wrap';
 470        const button = document.createElement('button');
 471        button.type = 'button';
 472        button.className = `tree-node${node.id === state.activeId ? ' active' : ''}${activePath.has(node.id) ? ' on-path' : ''}`;
 473        button.dataset.nodeId = node.id;
 474        button.setAttribute('aria-current', node.id === state.activeId ? 'true' : 'false');
 475        const children = grouped.get(node.id) || [];
 476        const isCollapsed = children.length > 0 && collapsed.has(node.id);
 477        const toggle = document.createElement(children.length ? 'button' : 'span');
 478        toggle.className = children.length ? 'toggle-subtree' : 'toggle-placeholder';
 479        if (children.length) {
 480          toggle.type = 'button';
 481          toggle.dataset.nodeId = node.id;
 482          toggle.setAttribute('aria-label', `${isCollapsed ? 'Expand' : 'Collapse'} branch: ${node.question}`);
 483          toggle.setAttribute('aria-expanded', String(!isCollapsed));
 484          toggle.textContent = isCollapsed ? '▸' : '▾';
 485        }
 486        button.innerHTML = `<span class="node-dot">${node.status === 'loading' ? '…' : (activePath.has(node.id) ? '●' : '○')}</span><span class="node-copy"><span class="node-title">${escapeHTML(node.question)}</span><span class="node-meta">${children.length} ${children.length === 1 ? 'reply' : 'branches'}${isCollapsed ? ' · hidden' : ''}</span></span>`;
 487        wrap.append(toggle, button);
 488        li.append(wrap);
 489        if (children.length && !isCollapsed) li.append(build(children));
 490        ul.append(li);
 491      }
 492      return ul;
 493    };
 494    els.tree.replaceChildren(build(roots));
 495    els.mapEmpty.hidden = state.nodes.length > 0;
 496    els.tree.hidden = state.nodes.length === 0;
 497    els.nodeCount.textContent = String(state.nodes.length);
 498    let branchCount = 0;
 499    for (const children of grouped.values()) branchCount += Math.max(0, children.length - 1);
 500    els.branchCount.textContent = String(branchCount);
 501  }
 502
 503  function revealNode(map, nodeId) {
 504    if (!nodeId) return;
 505    const hidden = new Set(map.collapsedIds);
 506    for (const node of pathTo(nodeId, map).slice(0, -1)) hidden.delete(node.id);
 507    map.collapsedIds = [...hidden];
 508  }
 509
 510  function toggleSubtree(nodeId, force) {
 511    if (!nodeById(nodeId)) return;
 512    const collapsed = new Set(state.collapsedIds);
 513    const shouldCollapse = force ?? !collapsed.has(nodeId);
 514    if (shouldCollapse) collapsed.add(nodeId);
 515    else collapsed.delete(nodeId);
 516    state.collapsedIds = [...collapsed];
 517    persistSoon();
 518    renderTree();
 519  }
 520
 521  function setAllSubtrees(collapsed) {
 522    if (!collapsed) state.collapsedIds = [];
 523    else {
 524      const parents = new Set(state.nodes.map(node => node.parentId).filter(Boolean));
 525      state.collapsedIds = [...parents];
 526    }
 527    persistSoon();
 528    renderTree();
 529  }
 530
 531  function updateTreeZoom(delta = 0) {
 532    treeZoom = Math.round(Math.max(.8, Math.min(1.4, treeZoom + delta)) * 10) / 10;
 533    els.tree.style.fontSize = `${.76 * treeZoom}rem`;
 534    els.tree.style.setProperty('--tree-indent', `${20 * treeZoom}px`);
 535    els.tree.style.setProperty('--tree-dot-size', `${17 * treeZoom}px`);
 536    els.tree.style.setProperty('--tree-node-pad-y', `${8 * treeZoom}px`);
 537    els.treeZoom.textContent = `${Math.round(treeZoom * 100)}%`;
 538    try { localStorage.setItem(TREE_ZOOM_KEY, String(treeZoom)); } catch {}
 539  }
 540
 541  function renderBranchContext() {
 542    const active = nodeById(state.activeId);
 543    const latest = state.nodes.at(-1);
 544    const branching = active && latest && active.id !== latest.id;
 545    els.branchContext.hidden = !branching;
 546    if (branching) els.branchLabel.textContent = active.question;
 547  }
 548
 549  function renderHistory() {
 550    const maps = workspace.maps
 551      .filter(map => map.nodes.length > 0 || map.attachments.length > 0)
 552      .sort((a, b) => b.updatedAt - a.updatedAt);
 553    const fragment = document.createDocumentFragment();
 554    for (const map of maps) {
 555      const row = document.createElement('div');
 556      row.className = 'history-row';
 557      const button = document.createElement('button');
 558      button.type = 'button';
 559      button.className = `history-item${map.id === workspace.activeMapId ? ' active' : ''}`;
 560      button.dataset.mapId = map.id;
 561      button.setAttribute('aria-current', map.id === workspace.activeMapId ? 'page' : 'false');
 562      const date = new Date(map.updatedAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
 563      const pdfMeta = map.attachments.length ? ` · ${map.attachments.length} PDF${map.attachments.length === 1 ? '' : 's'}` : '';
 564      button.innerHTML = `<span class="history-glyph" aria-hidden="true">${map.nodes.length || map.attachments.length ? '◇' : '+'}</span><span class="history-copy"><span class="history-title">${escapeHTML(map.title)}</span><span class="history-meta">${map.nodes.length} ${map.nodes.length === 1 ? 'node' : 'nodes'}${pdfMeta} · ${date}</span></span>`;
 565      const rename = document.createElement('button');
 566      rename.type = 'button';
 567      rename.className = 'rename-map';
 568      rename.dataset.mapId = map.id;
 569      rename.setAttribute('aria-label', `Rename conversation: ${map.title}`);
 570      rename.title = 'Rename this conversation';
 571      rename.textContent = '✎';
 572      const remove = document.createElement('button');
 573      remove.type = 'button';
 574      remove.className = 'delete-map';
 575      remove.dataset.mapId = map.id;
 576      remove.setAttribute('aria-label', `Delete conversation: ${map.title}`);
 577      remove.title = 'Delete this conversation';
 578      remove.textContent = '×';
 579      row.append(button, rename, remove);
 580      fragment.append(row);
 581    }
 582    els.historyList.replaceChildren(fragment);
 583    els.historyEmpty.hidden = maps.length > 0;
 584    els.historyList.hidden = maps.length === 0;
 585    if (els.conversationSearch.value.trim()) renderSearchResults();
 586    else els.searchResults.hidden = true;
 587  }
 588
 589  function buildSearchIndex() {
 590    const entries = [];
 591    for (const map of workspace.maps) {
 592      if (!map.nodes.length && !map.attachments.length) continue;
 593      entries.push({ mapId: map.id, nodeId: null, kind: 'Map', label: map.title, fields: [map.title] });
 594      for (const node of map.nodes) {
 595        entries.push({
 596          mapId: map.id, nodeId: node.id, kind: 'Node', label: node.question,
 597          fields: [node.question, node.answer || ''], mapTitle: map.title
 598        });
 599      }
 600      for (const file of map.attachments) {
 601        entries.push({ mapId: map.id, nodeId: null, kind: 'PDF', label: file.name, fields: [file.name], mapTitle: map.title });
 602      }
 603    }
 604    searchIndex = entries;
 605    return entries;
 606  }
 607
 608  function searchExcerpt(fields, expression) {
 609    for (const field of fields) {
 610      const source = String(field || '').replace(/\s+/g, ' ').trim();
 611      const index = source.search(expression);
 612      if (index < 0) continue;
 613      const start = Math.max(0, index - 45);
 614      const end = Math.min(source.length, index + 115);
 615      return `${start ? '…' : ''}${source.slice(start, end)}${end < source.length ? '…' : ''}`;
 616    }
 617    return '';
 618  }
 619
 620  function renderSearchResults() {
 621    const query = els.conversationSearch.value.trim();
 622    if (!query) {
 623      els.searchResults.hidden = true;
 624      els.historyList.hidden = false;
 625      els.historyEmpty.hidden = workspace.maps.some(map => map.nodes.length || map.attachments.length);
 626      return;
 627    }
 628    const expression = new RegExp(query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
 629    const matches = [];
 630    for (const entry of searchIndex || buildSearchIndex()) {
 631      const excerpt = searchExcerpt(entry.fields, expression);
 632      if (!excerpt) continue;
 633      matches.push({ ...entry, excerpt });
 634      if (matches.length >= 60) break;
 635    }
 636    els.searchResults.innerHTML = matches.length ? matches.map(entry => `
 637      <button class="search-result" type="button" data-map-id="${escapeHTML(entry.mapId)}"${entry.nodeId ? ` data-node-id="${escapeHTML(entry.nodeId)}"` : ''}>
 638        <span class="search-result-top"><strong>${escapeHTML(entry.label)}</strong><small>${escapeHTML(entry.kind)} · ${escapeHTML(entry.mapTitle || entry.label)}</small></span>
 639        <span class="search-excerpt">${escapeHTML(entry.excerpt)}</span>
 640      </button>`).join('') : `<p class="search-empty">No results for “${escapeHTML(query)}”.</p>`;
 641    els.searchResults.hidden = false;
 642    els.historyList.hidden = true;
 643    els.historyEmpty.hidden = true;
 644  }
 645
 646  function clearSearch() {
 647    clearTimeout(searchTimer);
 648    els.conversationSearch.value = '';
 649    renderSearchResults();
 650    renderHistory();
 651  }
 652
 653  function formatFileSize(bytes) {
 654    if (!bytes) return '';
 655    if (bytes < 1024 * 1024) return `${Math.max(1, Math.round(bytes / 1024))} KB`;
 656    return `${(bytes / (1024 * 1024)).toFixed(bytes < 10 * 1024 * 1024 ? 1 : 0)} MB`;
 657  }
 658
 659  function renderAttachments() {
 660    const fragment = document.createDocumentFragment();
 661    for (const file of state.attachments) {
 662      const chip = document.createElement('span');
 663      chip.className = 'attachment-chip';
 664      const available = file.provider === settings.provider;
 665      chip.classList.toggle('inactive-provider', !available);
 666      chip.title = `${file.name}${file.size ? ` · ${formatFileSize(file.size)}` : ''} · Uploaded to ${providerLabel(file.provider)}${available ? ' · Included with every question' : ' · Not sent with the selected provider'}`;
 667      chip.innerHTML = `<span class="pdf-badge" aria-hidden="true">PDF</span><span class="attachment-name">${escapeHTML(file.name)}</span>${available ? '' : `<span class="attachment-provider">${escapeHTML(providerLabel(file.provider))}</span>`}<button class="remove-attachment" type="button" data-file-id="${escapeHTML(file.id)}" aria-label="Remove ${escapeHTML(file.name)} from this map">×</button>`;
 668      fragment.append(chip);
 669    }
 670    if (uploadingPDFs && state.id === uploadTargetMapId) {
 671      const status = document.createElement('span');
 672      status.className = 'attachment-chip upload-status';
 673      status.innerHTML = '<span class="upload-spinner" aria-hidden="true"></span> Uploading…';
 674      fragment.append(status);
 675    }
 676    els.attachments.replaceChildren(fragment);
 677    els.attachments.hidden = !state.attachments.length && !(uploadingPDFs && state.id === uploadTargetMapId);
 678    els.uploadPDF.disabled = uploadingPDFs || Boolean(activeRequest);
 679  }
 680
 681  function renderAll(options) { renderConversation(options); renderTree(); renderHistory(); renderAttachments(); }
 682
 683  function updateStreamedNode(node) {
 684    if (state.activeId !== node.id || !state.nodes.includes(node)) return;
 685    const body = $(`.message[data-node-id="${CSS.escape(node.id)}"] .answer-body`, els.conversation);
 686    if (body) {
 687      const previousScroll = { left: window.scrollX, top: window.scrollY };
 688      body.innerHTML = answerHTML(node);
 689      if (window.scrollX !== previousScroll.left || window.scrollY !== previousScroll.top) {
 690        window.scrollTo({ ...previousScroll, behavior: 'auto' });
 691      }
 692    }
 693  }
 694
 695  function inputFor(map, parentId, question, provider = settings.provider) {
 696    const messages = [];
 697    for (const node of pathTo(parentId, map)) {
 698      if (provider === 'openrouter') {
 699        messages.push({ type: 'message', role: 'user', content: [{ type: 'input_text', text: node.question }] });
 700        if (node.answer) messages.push({
 701          type: 'message', role: 'assistant', id: `msg_${String(node.id).replace(/[^a-zA-Z0-9_-]/g, '')}`,
 702          status: 'completed', content: [{ type: 'output_text', text: node.answer, annotations: [] }]
 703        });
 704      } else {
 705        messages.push({ role: 'user', content: node.question });
 706        if (node.answer) messages.push({ role: 'assistant', content: node.answer });
 707      }
 708    }
 709    const content = map.attachments
 710      .filter(file => file.provider === provider)
 711      .map(file => ({ type: 'input_file', file_id: file.id, detail: file.detail || 'low' }));
 712    content.push({ type: 'input_text', text: question });
 713    const structured = provider === 'openrouter' || content.length > 1;
 714    messages.push(structured ? { type: 'message', role: 'user', content } : { role: 'user', content: question });
 715    return messages;
 716  }
 717
 718  function filesEndpoint(apiUrl = settings.apiUrl) {
 719    const url = new URL(apiUrl);
 720    if (!/\/responses\/?$/.test(url.pathname)) throw new Error('The configured endpoint is not a Responses API URL, so its Files endpoint cannot be derived.');
 721    url.pathname = url.pathname.replace(/\/responses\/?$/, '/files');
 722    url.search = '';
 723    url.hash = '';
 724    return url.toString();
 725  }
 726
 727  async function uploadPDFs(fileList) {
 728    const files = [...fileList];
 729    if (!files.length) return;
 730    if (activeRequest || uploadingPDFs) { showToast('Finish the current operation first'); return; }
 731    if (!settings.apiKey) { openSettings(); showToast(`Add a ${providerLabel()} API key before uploading`); return; }
 732
 733    const valid = files.filter(file => file.type === 'application/pdf' || file.name.toLowerCase().endsWith('.pdf'));
 734    if (valid.length !== files.length) { showToast('Only PDF files can be added'); return; }
 735    if (valid.some(file => file.size >= PDF_REQUEST_LIMIT)) { showToast('Each PDF must be smaller than 50 MB'); return; }
 736    const existingBytes = state.attachments.filter(file => file.provider === settings.provider).reduce((total, file) => total + file.size, 0);
 737    const addedBytes = valid.reduce((total, file) => total + file.size, 0);
 738    if (existingBytes + addedBytes >= PDF_REQUEST_LIMIT) { showToast('PDFs in one map must total less than 50 MB'); return; }
 739
 740    const targetMap = state;
 741    const connection = { ...settings };
 742    uploadingPDFs = true;
 743    uploadTargetMapId = targetMap.id;
 744    renderAttachments();
 745    let uploaded = 0;
 746    try {
 747      const endpoint = filesEndpoint(connection.apiUrl);
 748      for (const file of valid) {
 749        const form = new FormData();
 750        if (connection.provider === 'openai') form.append('purpose', 'user_data');
 751        form.append('file', file, file.name);
 752        const response = await fetch(endpoint, {
 753          method: 'POST', headers: requestHeaders(false, connection), body: form
 754        });
 755        if (!response.ok) {
 756          let message = `PDF upload failed (${response.status})`;
 757          try { const data = await response.json(); message = data.error?.message || message; } catch {}
 758          throw new Error(message);
 759        }
 760        const data = await response.json();
 761        if (!data.id) throw new Error('The Files API did not return a file ID.');
 762        targetMap.attachments.push({
 763          id: String(data.id), name: String(data.filename || file.name),
 764          size: Number(data.bytes ?? data.size_bytes) || file.size, createdAt: Date.now(), detail: 'low',
 765          provider: connection.provider
 766        });
 767        uploaded += 1;
 768        touchMap(targetMap);
 769        persistNow();
 770        if (state === targetMap) renderAll();
 771      }
 772      showToast(`${uploaded} PDF${uploaded === 1 ? '' : 's'} added to this map`);
 773    } catch (error) {
 774      showToast(error.message || 'PDF upload failed');
 775    } finally {
 776      uploadingPDFs = false;
 777      uploadTargetMapId = null;
 778      els.pdfInput.value = '';
 779      renderAll();
 780    }
 781  }
 782
 783  function removeAttachment(fileId) {
 784    const file = state.attachments.find(candidate => candidate.id === fileId);
 785    if (!file) return;
 786    if (!confirm(`Remove “${file.name}” from this map? The uploaded copy is not deleted from the API provider.`)) return;
 787    state.attachments = state.attachments.filter(candidate => candidate.id !== fileId);
 788    touchMap();
 789    persistNow();
 790    renderAll();
 791    showToast('PDF removed from this map');
 792  }
 793
 794  async function ask(question, parentId = state.activeId) {
 795    question = question.trim();
 796    if (!question) return;
 797    if (activeRequest) { showToast('Stop or finish the current response first'); return; }
 798    if (uploadingPDFs) { showToast('Wait for the PDF upload to finish'); return; }
 799    if (!settings.apiKey) { openSettings(); showToast(`Add a ${providerLabel()} API key to begin`); return; }
 800
 801    const requestMap = state;
 802    const connection = { ...settings };
 803    const node = {
 804      id: uid(), parentId: parentId || null, question, answer: '', status: 'loading', createdAt: Date.now(),
 805      provider: connection.provider, model: connection.model
 806    };
 807    requestMap.nodes.push(node);
 808    requestMap.activeId = node.id;
 809    revealNode(requestMap, node.id);
 810    refreshMapTitle(requestMap);
 811    touchMap(requestMap);
 812    persistSoon();
 813    renderAll({ scroll: true });
 814    setBusy(true);
 815    const controller = new AbortController();
 816    activeRequest = controller;
 817    let completedUsage = null;
 818
 819    try {
 820      const response = await fetch(connection.apiUrl, {
 821        method: 'POST',
 822        headers: requestHeaders(true, connection),
 823        body: JSON.stringify({ model: connection.model, instructions: connection.systemPrompt, input: inputFor(requestMap, parentId, question, connection.provider), stream: true }),
 824        signal: controller.signal
 825      });
 826      if (!response.ok) {
 827        let message = `API request failed (${response.status})`;
 828        try { const data = await response.json(); message = data.error?.message || message; } catch {}
 829        throw new Error(message);
 830      }
 831      if (!response.body) throw new Error('This browser did not provide a streaming response body.');
 832      await consumeSSE(response.body, event => {
 833        if (event.type === 'response.output_text.delta' || event.type === 'response.content_part.delta') node.answer += event.delta || '';
 834        if (event.type === 'response.completed' || event.type === 'response.done') {
 835          node.model = String(event.response?.model || node.model);
 836          completedUsage = event.response?.usage || event.usage || completedUsage;
 837        }
 838        if (event.type === 'response.failed') throw new Error(event.response?.error?.message || 'The model response failed.');
 839      }, () => updateStreamedNode(node));
 840      node.status = 'complete';
 841      if (completedUsage) await recordUsage(node.id, node.model || connection.model, connection.apiUrl, completedUsage, connection.provider);
 842    } catch (error) {
 843      node.status = 'error';
 844      node.error = error.name === 'AbortError' ? 'Response stopped.' : error.message;
 845    } finally {
 846      activeRequest = null;
 847      touchMap(requestMap);
 848      persistSoon();
 849      setBusy(false);
 850      renderAll();
 851    }
 852  }
 853
 854  async function consumeSSE(stream, onEvent, onPaint) {
 855    const reader = stream.getReader();
 856    const decoder = new TextDecoder();
 857    let buffer = '';
 858    let paintQueued = false;
 859    const queuePaint = () => {
 860      if (paintQueued) return;
 861      paintQueued = true;
 862      setTimeout(() => { paintQueued = false; onPaint(); }, 70);
 863    };
 864    const processBlock = block => {
 865      for (const line of block.split(/\r?\n/)) {
 866        if (!line.startsWith('data:')) continue;
 867        const data = line.slice(5).trim();
 868        if (!data || data === '[DONE]') continue;
 869        onEvent(JSON.parse(data));
 870        queuePaint();
 871      }
 872    };
 873    while (true) {
 874      const { done, value } = await reader.read();
 875      buffer += decoder.decode(value || new Uint8Array(), { stream: !done });
 876      const blocks = buffer.split(/\r?\n\r?\n/);
 877      buffer = blocks.pop() || '';
 878      for (const block of blocks) processBlock(block);
 879      if (done) break;
 880    }
 881    if (buffer.trim()) processBlock(buffer);
 882    onPaint();
 883  }
 884
 885  function setBusy(busy) {
 886    els.prompt.disabled = busy;
 887    els.send.textContent = busy ? '■' : '↑';
 888    els.send.setAttribute('aria-label', busy ? 'Stop response' : 'Send message');
 889    els.uploadPDF.disabled = busy || uploadingPDFs;
 890  }
 891
 892  function openSettings() {
 893    settingsDraftProfiles = structuredClone(settings.profiles);
 894    els.provider.value = settings.provider;
 895    els.openaiApiKey.value = settingsDraftProfiles.openai.apiKey || '';
 896    els.openrouterApiKey.value = settingsDraftProfiles.openrouter.apiKey || '';
 897    els.openaiModel.value = settingsDraftProfiles.openai.model || PROVIDERS.openai.model;
 898    els.openrouterModel.value = settingsDraftProfiles.openrouter.model || PROVIDERS.openrouter.model;
 899    els.openaiApiUrl.value = settingsDraftProfiles.openai.apiUrl || PROVIDERS.openai.apiUrl;
 900    els.openrouterApiUrl.value = settingsDraftProfiles.openrouter.apiUrl || PROVIDERS.openrouter.apiUrl;
 901    fillModelOptions(els.openaiModelOptions, PROVIDERS.openai.models);
 902    fillModelOptions(els.openrouterModelOptions, PROVIDERS.openrouter.models);
 903    updateProviderCards();
 904    els.systemPrompt.value = settings.systemPrompt;
 905    els.settings.showModal();
 906    setTimeout(() => (settings.provider === 'openrouter' ? els.openrouterApiKey : els.openaiApiKey).focus(), 50);
 907  }
 908
 909  function fillModelOptions(list, models) {
 910    list.replaceChildren(...models.map(model => Object.assign(document.createElement('option'), { value: model })));
 911  }
 912
 913  function captureProviderForms() {
 914    if (!settingsDraftProfiles) return;
 915    settingsDraftProfiles = {
 916      openai: {
 917        apiKey: els.openaiApiKey.value.trim(),
 918        model: els.openaiModel.value.trim() || PROVIDERS.openai.model,
 919        apiUrl: els.openaiApiUrl.value.trim() || PROVIDERS.openai.apiUrl
 920      },
 921      openrouter: {
 922        apiKey: els.openrouterApiKey.value.trim(),
 923        model: els.openrouterModel.value.trim() || PROVIDERS.openrouter.model,
 924        apiUrl: els.openrouterApiUrl.value.trim() || PROVIDERS.openrouter.apiUrl
 925      }
 926    };
 927  }
 928
 929  function updateProviderCards() {
 930    document.querySelectorAll('[data-provider-config]').forEach(card => {
 931      card.classList.toggle('active', card.dataset.providerConfig === els.provider.value);
 932    });
 933  }
 934
 935  function showToast(message) {
 936    els.toast.textContent = message;
 937    els.toast.classList.add('show');
 938    clearTimeout(toastTimer);
 939    toastTimer = setTimeout(() => els.toast.classList.remove('show'), 2200);
 940  }
 941
 942  function updateKeyStatus() {
 943    els.keyStatus.classList.toggle('ready', Boolean(settings.apiKey));
 944    els.activeModel.textContent = settings.model;
 945    els.activeProvider.textContent = providerLabel();
 946    els.activeConnection.title = `${providerLabel()} · ${settings.model} — open settings`;
 947    els.activeConnection.setAttribute('aria-label', `Current model: ${settings.model} through ${providerLabel()}. Open API settings`);
 948    const button = $('#open-settings');
 949    button.title = `${providerLabel()} · ${settings.model}`;
 950    button.setAttribute('aria-label', `API settings — ${providerLabel()}, ${settings.model}`);
 951  }
 952
 953  function updateThemeButton() {
 954    const dark = document.documentElement.dataset.theme === 'dark';
 955    const button = $('#theme-toggle');
 956    button.querySelector('span').textContent = dark ? '☀' : '☾';
 957    button.setAttribute('aria-label', `Switch to ${dark ? 'light' : 'dark'} theme`);
 958    button.title = `Switch to ${dark ? 'light' : 'dark'} theme`;
 959  }
 960
 961  function toggleTheme() {
 962    const next = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
 963    document.documentElement.dataset.theme = next;
 964    try { localStorage.setItem(THEME_KEY, next); } catch {}
 965    updateThemeButton();
 966  }
 967
 968  function priceForModel(model) {
 969    const key = String(model || '').toLowerCase();
 970    return MODEL_PRICES.find(price => price.match.test(key)) || null;
 971  }
 972
 973  function isOpenAIEndpoint(apiUrl) {
 974    try { return new URL(apiUrl).hostname === 'api.openai.com'; }
 975    catch { return false; }
 976  }
 977
 978  async function openRouterPriceForModel(model) {
 979    const key = String(model || '').trim();
 980    if (!key.includes('/')) return null;
 981    const cached = openRouterPrices[key];
 982    const validCached = cached && Number.isFinite(Number(cached.input)) && Number.isFinite(Number(cached.output));
 983    if (validCached && Date.now() - Number(cached.checkedAt) < PRICE_CACHE_TTL) return cached;
 984    try {
 985      const path = key.split('/').map(encodeURIComponent).join('/');
 986      const response = await fetch(`https://openrouter.ai/api/v1/model/${path}`, {
 987        headers: { 'Accept': 'application/json' }
 988      });
 989      if (!response.ok) return validCached ? cached : null;
 990      const pricing = (await response.json()).data?.pricing;
 991      const prompt = pricing?.prompt == null ? NaN : Number(pricing.prompt);
 992      const completion = pricing?.completion == null ? NaN : Number(pricing.completion);
 993      const cacheRead = pricing?.input_cache_read == null ? NaN : Number(pricing.input_cache_read);
 994      if (!Number.isFinite(prompt) || !Number.isFinite(completion)) return validCached ? cached : null;
 995      const price = {
 996        input: prompt * 1_000_000,
 997        cached: (Number.isFinite(cacheRead) ? cacheRead : prompt) * 1_000_000,
 998        output: completion * 1_000_000,
 999        request: Number(pricing?.request) || 0,
1000        checkedAt: Date.now(),
1001        source: 'openrouter'
1002      };
1003      openRouterPrices[key] = price;
1004      persistOpenRouterPrices();
1005      return price;
1006    } catch { return validCached ? cached : null; }
1007  }
1008
1009  async function recordUsage(nodeId, model, apiUrl, rawUsage, provider) {
1010    if (usageRecords.some(record => record.nodeId === nodeId)) return;
1011    const inputTokens = Number(rawUsage.input_tokens) || 0;
1012    const outputTokens = Number(rawUsage.output_tokens) || 0;
1013    const cachedTokens = Math.min(inputTokens, Number(rawUsage.input_tokens_details?.cached_tokens) || 0);
1014    const totalTokens = Number(rawUsage.total_tokens) || inputTokens + outputTokens;
1015    const price = provider === 'openrouter'
1016      ? await openRouterPriceForModel(model)
1017      : (isOpenAIEndpoint(apiUrl) ? priceForModel(model) : null);
1018    const costUSD = price
1019      ? ((((inputTokens - cachedTokens) * price.input) + (cachedTokens * price.cached) + (outputTokens * price.output)) / 1_000_000) + (Number(price.request) || 0)
1020      : null;
1021    usageRecords.push({
1022      id: uid(), nodeId, timestamp: Date.now(), model: String(model || 'unknown'),
1023      inputTokens, cachedTokens, outputTokens, totalTokens, costUSD,
1024      rates: price ? {
1025        input: price.input, cached: price.cached, output: price.output,
1026        request: Number(price.request) || 0, source: price.source || 'openai', checkedAt: price.checkedAt || Date.now()
1027      } : null
1028    });
1029    // Keep bounded history while retaining roughly a year of normal personal use.
1030    usageRecords = usageRecords.slice(-2000);
1031    try { localStorage.setItem(USAGE_KEY, JSON.stringify(usageRecords)); }
1032    catch { showToast('Usage was returned, but local usage history is full'); }
1033    updateUsageButton();
1034  }
1035
1036  function currentMonthRecords() {
1037    const now = new Date();
1038    return usageRecords.filter(record => {
1039      const date = new Date(record.timestamp);
1040      return date.getFullYear() === now.getFullYear() && date.getMonth() === now.getMonth();
1041    });
1042  }
1043
1044  function sum(records, key) { return records.reduce((total, record) => total + (Number(record[key]) || 0), 0); }
1045
1046  function formatTokens(value, compact = false) {
1047    const number = Number(value) || 0;
1048    if (!compact || number < 1000) return Math.round(number).toLocaleString();
1049    if (number < 1_000_000) return `${(number / 1000).toFixed(number < 10_000 ? 1 : 0)}K`;
1050    return `${(number / 1_000_000).toFixed(number < 10_000_000 ? 1 : 0)}M`;
1051  }
1052
1053  function formatCost(value) {
1054    if (!Number.isFinite(value)) return 'Unpriced';
1055    if (value > 0 && value < .01) return '<$0.01';
1056    return value.toLocaleString(undefined, { style: 'currency', currency: 'USD', minimumFractionDigits: 2, maximumFractionDigits: value < 1 ? 4 : 2 });
1057  }
1058
1059  function updateUsageButton() {
1060    const total = sum(currentMonthRecords(), 'totalTokens');
1061    els.monthTokens.textContent = formatTokens(total, true);
1062    const label = `${formatTokens(total)} tokens tracked this month`;
1063    $('#open-usage').title = label;
1064    $('#open-usage').setAttribute('aria-label', `${label}. Open API usage details`);
1065  }
1066
1067  function usageRowsByModel(records) {
1068    const groups = new Map();
1069    for (const record of records) {
1070      const model = String(record.model || 'unknown');
1071      if (!groups.has(model)) groups.set(model, { model, totalTokens: 0, costUSD: 0, unpriced: 0 });
1072      const group = groups.get(model);
1073      group.totalTokens += Number(record.totalTokens) || 0;
1074      if (Number.isFinite(record.costUSD)) group.costUSD += record.costUSD;
1075      else group.unpriced += 1;
1076    }
1077    return [...groups.values()].sort((a, b) => b.totalTokens - a.totalTokens);
1078  }
1079
1080  function renderUsage() {
1081    const records = currentMonthRecords().sort((a, b) => b.timestamp - a.timestamp);
1082    const totalCost = records.reduce((total, record) => total + (Number.isFinite(record.costUSD) ? record.costUSD : 0), 0);
1083    const unpriced = records.filter(record => !Number.isFinite(record.costUSD)).length;
1084    els.usageMonth.textContent = new Date().toLocaleDateString(undefined, { month: 'long', year: 'numeric' });
1085    els.usageTotal.textContent = formatTokens(sum(records, 'totalTokens'));
1086    els.usageCost.textContent = records.length && unpriced === records.length
1087      ? 'Unpriced'
1088      : `${formatCost(totalCost)}${unpriced ? ' +' : ''}`;
1089    els.usageRequests.textContent = formatTokens(records.length);
1090    els.usageInput.textContent = formatTokens(sum(records, 'inputTokens'));
1091    els.usageCached.textContent = formatTokens(sum(records, 'cachedTokens'));
1092    els.usageOutput.textContent = formatTokens(sum(records, 'outputTokens'));
1093
1094    const groups = usageRowsByModel(records);
1095    els.usageModels.innerHTML = groups.length ? groups.map(group => `
1096      <div class="usage-row">
1097        <span class="model-name" title="${escapeHTML(group.model)}">${escapeHTML(group.model)}</span>
1098        <span class="row-tokens">${formatTokens(group.totalTokens)} tokens</span>
1099        <span class="row-cost">${group.unpriced ? 'Partly unpriced' : formatCost(group.costUSD)}</span>
1100      </div>`).join('') : '<p class="usage-empty">No tracked requests this month.</p>';
1101
1102    els.usageRecent.innerHTML = records.length ? records.slice(0, 12).map(record => `
1103      <div class="usage-row">
1104        <span class="model-name">${new Date(record.timestamp).toLocaleString(undefined, { month: 'short', day: 'numeric', hour: 'numeric', minute: '2-digit' })}</span>
1105        <span class="row-tokens">${formatTokens(record.totalTokens)} tokens</span>
1106        <span class="row-cost">${formatCost(record.costUSD)}</span>
1107      </div>`).join('') : '<p class="usage-empty">Completed requests will appear here.</p>';
1108
1109    els.usageNote.textContent = unpriced
1110      ? `${unpriced} request${unpriced === 1 ? '' : 's'} could not be estimated because its model price could not be resolved.`
1111      : 'Estimates use the rate recorded when each request completed: the local OpenAI table or OpenRouter\'s model-pricing API.';
1112  }
1113
1114  function openUsage() {
1115    renderUsage();
1116    const openRouter = settings.provider === 'openrouter';
1117    els.usageDashboard.href = openRouter ? 'https://openrouter.ai/activity' : 'https://platform.openai.com/usage';
1118    els.usageDashboard.textContent = `${openRouter ? 'OpenRouter' : 'OpenAI'} dashboard ↗`;
1119    els.usageDialog.showModal();
1120  }
1121
1122  function createNewMap() {
1123    const existingBlank = workspace.maps.find(map => map.nodes.length === 0 && map.attachments.length === 0);
1124    const map = existingBlank || blankMap();
1125    if (!existingBlank) workspace.maps.push(map);
1126    workspace.activeMapId = map.id;
1127    state = map;
1128    els.conversationSearch.value = '';
1129    persistNow();
1130    renderAll();
1131    closeHistoryOnSmallScreen();
1132    window.scrollTo({ top: 0, behavior: 'smooth' });
1133    els.prompt.focus();
1134  }
1135
1136  function switchMap(mapId, nodeId = null) {
1137    const map = workspace.maps.find(candidate => candidate.id === mapId);
1138    if (!map) { closeHistoryOnSmallScreen(); return; }
1139    workspace.activeMapId = map.id;
1140    state = map;
1141    state.activeId = nodeId && nodeById(nodeId, state) ? nodeId : (state.nodes.at(-1)?.id || null);
1142    revealNode(state, state.activeId);
1143    persistSoon();
1144    hideSelectionMenu();
1145    renderAll({ scroll: state.activeId ? (nodeId ? true : 'bottom') : false });
1146    closeHistoryOnSmallScreen();
1147  }
1148
1149  function activateNode(nodeId, scroll = true) {
1150    if (!nodeById(nodeId)) return;
1151    state.activeId = nodeId;
1152    revealNode(state, nodeId);
1153    persistSoon();
1154    renderAll({ scroll });
1155    document.body.classList.remove('map-open');
1156  }
1157
1158  function visibleTreeNodeIds() {
1159    return [...els.tree.querySelectorAll('.tree-node')].map(button => button.dataset.nodeId);
1160  }
1161
1162  function moveVisibleNode(offset) {
1163    const ids = visibleTreeNodeIds();
1164    if (!ids.length) return;
1165    const current = Math.max(0, ids.indexOf(state.activeId));
1166    activateNode(ids[Math.max(0, Math.min(ids.length - 1, current + offset))]);
1167  }
1168
1169  function moveMap(offset) {
1170    const maps = workspace.maps
1171      .filter(map => map.nodes.length || map.attachments.length)
1172      .sort((a, b) => b.updatedAt - a.updatedAt);
1173    if (!maps.length) return;
1174    const current = Math.max(0, maps.findIndex(map => map.id === state.id));
1175    switchMap(maps[Math.max(0, Math.min(maps.length - 1, current + offset))].id);
1176  }
1177
1178  function focusConversationSearch() {
1179    document.body.classList.remove('history-collapsed', 'map-open');
1180    if (matchMedia('(max-width: 1100px)').matches) document.body.classList.add('history-open');
1181    updateHistoryToggle();
1182    els.conversationSearch.focus();
1183    els.conversationSearch.select();
1184  }
1185
1186  function handleVimNavigation(event) {
1187    if (event.defaultPrevented || event.ctrlKey || event.metaKey || event.altKey) return;
1188    const editable = event.target.closest?.('input, textarea, select, [contenteditable="true"]');
1189    if (editable) {
1190      if (event.key === 'Escape') {
1191        event.preventDefault();
1192        if (editable === els.conversationSearch) clearSearch();
1193        editable.blur();
1194      }
1195      return;
1196    }
1197    if ($('dialog[open]')) return;
1198    if (pendingG && event.key !== 'g') {
1199      clearTimeout(pendingGTimer);
1200      pendingG = false;
1201    }
1202    if (event.key === '?') { event.preventDefault(); els.shortcutsDialog.showModal(); return; }
1203    if (event.key === '/') { event.preventDefault(); focusConversationSearch(); return; }
1204    if (event.key === 'i') { event.preventDefault(); els.prompt.focus(); return; }
1205    if (event.key === 'j') { event.preventDefault(); moveVisibleNode(1); return; }
1206    if (event.key === 'k') { event.preventDefault(); moveVisibleNode(-1); return; }
1207    if (event.key === 'J') { event.preventDefault(); moveMap(1); return; }
1208    if (event.key === 'K') { event.preventDefault(); moveMap(-1); return; }
1209    if (event.key === 'h') {
1210      const parentId = nodeById(state.activeId)?.parentId;
1211      if (parentId) { event.preventDefault(); activateNode(parentId); }
1212      return;
1213    }
1214    if (event.key === 'l') {
1215      const children = childrenOf(state.activeId);
1216      if (!children.length) return;
1217      event.preventDefault();
1218      if (state.collapsedIds.includes(state.activeId)) toggleSubtree(state.activeId, false);
1219      else activateNode(children[0].id);
1220      return;
1221    }
1222    if (event.key === ' ') {
1223      if (childrenOf(state.activeId).length) { event.preventDefault(); toggleSubtree(state.activeId); }
1224      return;
1225    }
1226    if (event.key === 'G') {
1227      const ids = visibleTreeNodeIds();
1228      if (ids.length) { event.preventDefault(); activateNode(ids.at(-1)); }
1229      return;
1230    }
1231    if (event.key === 'g') {
1232      event.preventDefault();
1233      if (pendingG) {
1234        clearTimeout(pendingGTimer);
1235        pendingG = false;
1236        const ids = visibleTreeNodeIds();
1237        if (ids.length) activateNode(ids[0]);
1238      } else {
1239        pendingG = true;
1240        pendingGTimer = setTimeout(() => { pendingG = false; }, 900);
1241      }
1242    }
1243  }
1244
1245  function closeHistoryOnSmallScreen() {
1246    if (matchMedia('(max-width: 1100px)').matches) document.body.classList.remove('history-open');
1247    updateHistoryToggle();
1248  }
1249
1250  function updateHistoryToggle() {
1251    const small = matchMedia('(max-width: 1100px)').matches;
1252    const open = small ? document.body.classList.contains('history-open') : !document.body.classList.contains('history-collapsed');
1253    els.historyToggle.setAttribute('aria-expanded', String(open));
1254  }
1255
1256  function toggleHistory() {
1257    if (matchMedia('(max-width: 1100px)').matches) {
1258      document.body.classList.remove('history-collapsed');
1259      document.body.classList.toggle('history-open');
1260      if (document.body.classList.contains('history-open')) document.body.classList.remove('map-open');
1261    } else document.body.classList.toggle('history-collapsed');
1262    updateHistoryToggle();
1263  }
1264
1265  function clearChatHistory(message = 'Clear all saved conversations? Your API key and usage records will be kept. Uploaded API files will not be deleted.') {
1266    if (!workspace.maps.some(map => map.nodes.length || map.attachments.length)) { showToast('Chat history is already empty'); return false; }
1267    if (!confirm(message)) return false;
1268    if (activeRequest) activeRequest.abort();
1269    const map = blankMap();
1270    workspace = { version: 2, maps: [map], activeMapId: map.id };
1271    state = map;
1272    searchIndex = null;
1273    els.conversationSearch.value = '';
1274    persistNow();
1275    renderAll();
1276    showToast('All conversations cleared');
1277    return true;
1278  }
1279
1280  function deleteMap(mapId) {
1281    const map = workspace.maps.find(candidate => candidate.id === mapId);
1282    if (!map) return;
1283    if (uploadingPDFs && uploadTargetMapId === map.id) { showToast('Wait for this map’s PDF upload to finish'); return; }
1284    const remoteNote = map.attachments.length ? ' Uploaded API files will not be deleted.' : '';
1285    if (!confirm(`Delete “${map.title}” and its entire conversation? This cannot be undone.${remoteNote}`)) return;
1286    if (activeRequest && map.nodes.some(node => node.status === 'loading')) activeRequest.abort();
1287
1288    workspace.maps = workspace.maps.filter(candidate => candidate.id !== map.id);
1289    searchIndex = null;
1290    if (!workspace.maps.length) workspace.maps.push(blankMap());
1291    if (state === map) {
1292      const next = [...workspace.maps]
1293        .filter(candidate => candidate.nodes.length || candidate.attachments.length)
1294        .sort((a, b) => b.updatedAt - a.updatedAt)[0] || workspace.maps[0];
1295      workspace.activeMapId = next.id;
1296      state = next;
1297      state.activeId = state.nodes.at(-1)?.id || null;
1298      revealNode(state, state.activeId);
1299    }
1300    persistNow();
1301    renderAll({ scroll: state.activeId ? 'bottom' : false });
1302    showToast('Conversation deleted');
1303  }
1304
1305  function renameMap(mapId) {
1306    const map = workspace.maps.find(candidate => candidate.id === mapId);
1307    if (!map) return;
1308    const value = prompt('Rename this conversation. Leave blank to restore its automatic title.', map.title);
1309    if (value === null) return;
1310    const title = value.replace(/\s+/g, ' ').trim();
1311    if (title) {
1312      map.title = title.slice(0, 120);
1313      map.titleCustom = true;
1314    } else {
1315      map.titleCustom = false;
1316      refreshMapTitle(map);
1317    }
1318    touchMap(map);
1319    persistNow();
1320    renderHistory();
1321    showToast(title ? 'Conversation renamed' : 'Automatic title restored');
1322  }
1323
1324  function showSelectionMenu(text, nodeId, rect) {
1325    selectedText = { text: text.slice(0, 5000), nodeId };
1326    els.selectionPreview.textContent = text.length > 240 ? `${text.slice(0, 240)}…` : text;
1327    els.selectionMenu.hidden = false;
1328    const width = 330;
1329    const left = Math.max(12, Math.min(innerWidth - width - 12, rect.left + rect.width / 2 - width / 2));
1330    const estimatedHeight = 235;
1331    const top = rect.bottom + estimatedHeight < innerHeight ? rect.bottom + 10 : Math.max(10, rect.top - estimatedHeight - 8);
1332    Object.assign(els.selectionMenu.style, { left: `${left}px`, top: `${top}px` });
1333  }
1334
1335  function hideSelectionMenu() { els.selectionMenu.hidden = true; selectedText = null; }
1336
1337  els.composer.addEventListener('submit', event => {
1338    event.preventDefault();
1339    if (activeRequest) { activeRequest.abort(); return; }
1340    const question = els.prompt.value;
1341    els.prompt.value = '';
1342    els.prompt.style.height = '';
1343    ask(question);
1344  });
1345  els.prompt.addEventListener('keydown', event => {
1346    if (event.key === 'Enter' && !event.shiftKey && !event.isComposing) { event.preventDefault(); els.composer.requestSubmit(); }
1347  });
1348  els.prompt.addEventListener('input', () => {
1349    els.prompt.style.height = 'auto';
1350    els.prompt.style.height = `${Math.min(els.prompt.scrollHeight, 180)}px`;
1351  });
1352  document.addEventListener('click', event => {
1353    const starter = event.target.closest('.starter');
1354    if (starter) { els.prompt.value = starter.dataset.prompt; els.prompt.focus(); }
1355    const historyItem = event.target.closest('.history-item');
1356    if (historyItem) { switchMap(historyItem.dataset.mapId); return; }
1357    const searchResult = event.target.closest('.search-result');
1358    if (searchResult) {
1359      const { mapId, nodeId } = searchResult.dataset;
1360      clearSearch();
1361      switchMap(mapId, nodeId || null);
1362      return;
1363    }
1364    const renameConversation = event.target.closest('.rename-map');
1365    if (renameConversation) { renameMap(renameConversation.dataset.mapId); return; }
1366    const deleteConversation = event.target.closest('.delete-map');
1367    if (deleteConversation) { deleteMap(deleteConversation.dataset.mapId); return; }
1368    const removeFile = event.target.closest('.remove-attachment');
1369    if (removeFile) { removeAttachment(removeFile.dataset.fileId); return; }
1370    const subtreeToggle = event.target.closest('.toggle-subtree');
1371    if (subtreeToggle) { toggleSubtree(subtreeToggle.dataset.nodeId); return; }
1372    const treeNode = event.target.closest('.tree-node');
1373    if (treeNode) { activateNode(treeNode.dataset.nodeId); return; }
1374    const branch = event.target.closest('.branch-here');
1375    if (branch) { state.activeId = branch.closest('.message').dataset.nodeId; persistSoon(); renderAll(); els.prompt.focus(); }
1376    const retry = event.target.closest('.retry-node');
1377    if (retry) { const old = nodeById(retry.closest('.message').dataset.nodeId); state.activeId = old.parentId; ask(old.question, old.parentId); }
1378    const copy = event.target.closest('.copy-answer');
1379    if (copy) { const node = nodeById(copy.closest('.message').dataset.nodeId); navigator.clipboard.writeText(node.answer).then(() => showToast('Answer copied')); }
1380  });
1381  document.addEventListener('mouseup', event => {
1382    if (event.target.closest('.selection-menu')) return;
1383    requestAnimationFrame(() => {
1384      const selection = getSelection();
1385      const text = selection?.toString().trim();
1386      if (!text || text.length < 2 || !selection.rangeCount) return;
1387      const answer = selection.anchorNode?.parentElement?.closest('.answer-body');
1388      if (!answer || !answer.contains(selection.focusNode)) return;
1389      const message = answer.closest('.message');
1390      showSelectionMenu(text, message.dataset.nodeId, selection.getRangeAt(0).getBoundingClientRect());
1391    });
1392  });
1393
1394  $('#ask-selection').addEventListener('click', () => {
1395    if (!selectedText) return;
1396    const action = els.selectionAction.value === 'custom' ? els.selectionCustom.value.trim() : els.selectionAction.value;
1397    if (!action) { els.selectionCustom.focus(); return; }
1398    const question = `${action}\n\nSelected passage:\n> ${selectedText.text.replace(/\n/g, '\n> ')}`;
1399    const parentId = selectedText.nodeId;
1400    hideSelectionMenu();
1401    getSelection()?.removeAllRanges();
1402    ask(question, parentId);
1403  });
1404  els.selectionAction.addEventListener('change', () => {
1405    els.selectionCustom.hidden = els.selectionAction.value !== 'custom';
1406    if (!els.selectionCustom.hidden) els.selectionCustom.focus();
1407  });
1408  $('#close-selection').addEventListener('click', hideSelectionMenu);
1409  window.addEventListener('scroll', hideSelectionMenu, { passive: true });
1410  $('#open-settings').addEventListener('click', openSettings);
1411  els.activeConnection.addEventListener('click', openSettings);
1412  $('#open-usage').addEventListener('click', openUsage);
1413  $('#theme-toggle').addEventListener('click', toggleTheme);
1414  $('#toggle-history').addEventListener('click', toggleHistory);
1415  els.conversationSearch.addEventListener('input', () => {
1416    clearTimeout(searchTimer);
1417    searchTimer = setTimeout(renderSearchResults, 110);
1418  });
1419  els.conversationSearch.addEventListener('keydown', event => {
1420    if (event.key !== 'Enter') return;
1421    const first = $('.search-result', els.searchResults);
1422    if (first) { event.preventDefault(); first.click(); }
1423  });
1424  $('#study-lab-home').addEventListener('click', event => { event.preventDefault(); createNewMap(); });
1425  $('#new-map-sidebar').addEventListener('click', createNewMap);
1426  els.uploadPDF.addEventListener('click', () => els.pdfInput.click());
1427  els.pdfInput.addEventListener('change', () => uploadPDFs(els.pdfInput.files));
1428  $('#close-settings').addEventListener('click', () => els.settings.close());
1429  $('#close-usage').addEventListener('click', () => els.usageDialog.close());
1430  $('#open-shortcuts').addEventListener('click', () => els.shortcutsDialog.showModal());
1431  $('#close-shortcuts').addEventListener('click', () => els.shortcutsDialog.close());
1432  $('#expand-all-nodes').addEventListener('click', () => setAllSubtrees(false));
1433  $('#collapse-all-nodes').addEventListener('click', () => setAllSubtrees(true));
1434  $('#zoom-out-tree').addEventListener('click', () => updateTreeZoom(-.1));
1435  $('#zoom-in-tree').addEventListener('click', () => updateTreeZoom(.1));
1436  $('#reset-usage').addEventListener('click', () => {
1437    if (!usageRecords.length || confirm('Reset the locally tracked API usage history? This cannot be undone.')) {
1438      usageRecords = [];
1439      localStorage.removeItem(USAGE_KEY);
1440      updateUsageButton();
1441      renderUsage();
1442      showToast('Local usage history reset');
1443    }
1444  });
1445  document.querySelectorAll('.toggle-key').forEach(button => button.addEventListener('click', event => {
1446    const input = document.getElementById(event.currentTarget.dataset.keyInput);
1447    const show = input.type === 'password';
1448    input.type = show ? 'text' : 'password';
1449    event.currentTarget.textContent = show ? 'Hide' : 'Show';
1450    event.currentTarget.setAttribute('aria-label', `${show ? 'Hide' : 'Show'} ${input.id === 'openrouter-api-key' ? 'OpenRouter' : 'OpenAI'} API key`);
1451  }));
1452  els.provider.addEventListener('change', updateProviderCards);
1453  $('#settings-form').addEventListener('submit', event => {
1454    event.preventDefault();
1455    captureProviderForms();
1456    settings = normalizeSettings({ provider: els.provider.value, profiles: settingsDraftProfiles, systemPrompt: els.systemPrompt.value.trim() });
1457    localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
1458    settingsDraftProfiles = null;
1459    updateKeyStatus(); renderAttachments(); els.settings.close(); showToast(`${providerLabel()} settings saved`);
1460  });
1461  $('#forget-key').addEventListener('click', () => {
1462    const provider = els.provider.value;
1463    const input = provider === 'openrouter' ? els.openrouterApiKey : els.openaiApiKey;
1464    input.value = '';
1465    settingsDraftProfiles[provider].apiKey = '';
1466    const profiles = structuredClone(settings.profiles);
1467    profiles[provider].apiKey = '';
1468    settings = normalizeSettings({ provider: settings.provider, profiles, systemPrompt: settings.systemPrompt });
1469    localStorage.setItem(SETTINGS_KEY, JSON.stringify(settings));
1470    updateKeyStatus();
1471    showToast(`${providerLabel(provider)} API key removed`);
1472  });
1473  $('#clear-history').addEventListener('click', () => clearChatHistory());
1474  $('#clear-branch').addEventListener('click', () => { state.activeId = state.nodes.at(-1)?.id || null; revealNode(state, state.activeId); persistSoon(); renderAll({ scroll: true }); });
1475  $('#collapse-map').addEventListener('click', () => { document.body.classList.remove('map-open'); document.body.classList.add('map-collapsed'); $('#expand-map').hidden = false; });
1476  $('#expand-map').addEventListener('click', () => { document.body.classList.remove('map-collapsed', 'history-open'); document.body.classList.add('map-open'); $('#expand-map').hidden = true; updateHistoryToggle(); });
1477  addEventListener('resize', updateHistoryToggle, { passive: true });
1478  document.addEventListener('keydown', handleVimNavigation);
1479
1480  updateKeyStatus();
1481  updateThemeButton();
1482  updateUsageButton();
1483  updateHistoryToggle();
1484  updateTreeZoom();
1485  state.activeId = state.nodes.at(-1)?.id || null;
1486  revealNode(state, state.activeId);
1487  renderAll();
1488})();