truemap-cli 0.3.0 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -6,12 +6,13 @@
6
6
  const S = {
7
7
  placeholder: 'Ask about this page', placeholderNotes: 'Add a message (optional)',
8
8
  drawPrompt: 'Read this project and draw its blueprint as .truemap/index.html, then open it for me.',
9
- ok: 'Matches the code', changed: (n) => `${n} changed in code`, broken: (n) => `${n} no longer match`,
9
+ ok: 'Matches the code', changed: (n) => `Map may be out of date (${n})`, broken: (n) => `Map out of date (${n})`,
10
10
  fixPrompt: (p, c, b) => `Check ${p} against the code and update it: ${[b && `${b} anchor(s) no longer match`, c && `${c} anchor(s) whose code changed after the page was written`].filter(Boolean).join(', ')}.`,
11
11
  chose: 'Chose', fromPage: 'Sent by the page’s own script', waiting: 'Waiting for the agent', you: 'You',
12
- state: {
12
+ state: { listening: 'Listening', working: 'Working', idle: 'Stopped listening', stale: 'No reply yet', offline: 'Not listening', closed: 'Closed' },
13
+ stateLong: {
13
14
  listening: (a) => `${a} is listening`, working: (a) => `${a} is working`, idle: (a) => `${a} stopped listening`, stale: (a) => `No reply from ${a} yet`,
14
- offline: () => 'No agent listening', closed: () => 'Workspace closed',
15
+ offline: () => 'No agent is listening', closed: () => 'This workspace is closed',
15
16
  },
16
17
  };
17
18
 
@@ -20,7 +21,7 @@
20
21
  const state = {
21
22
  pages: [], check: { results: [] }, page: null, history: [], pending: new Set(), scroll: {},
22
23
  notes: [], agent: { state: 'offline', name: '', since: 0 }, progress: '', cmd: 'npx -y truemap-cli',
23
- annotate: false, annotateTouched: false, conn: 'live', frameFocusAt: 0,
24
+ conn: 'live', frameFocusAt: 0,
24
25
  };
25
26
 
26
27
  const store = {
@@ -46,11 +47,18 @@
46
47
  .replace(/`([^`]+)`/g, '<code>$1</code>')
47
48
  .replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
48
49
  .replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?![*\w])/g, '$1<em>$2</em>')
49
- .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, href) => {
50
+ .replace(/!\[([^\]]*)\]\(([^)\s]+)\)/g, (all, alt, href) => {
51
+ const src = /^https:\/\/[^\s"'<>]+$/i.test(href) ? href
52
+ : /^[^\s"'<>:]+\.(png|jpe?g|gif|webp)$/i.test(href) || /^[a-z]:[\\/][^\s"'<>]+\.(png|jpe?g|gif|webp)$/i.test(href) ? `/api/image?path=${encodeURIComponent(href.replace(/&amp;/g, '&'))}&t=${encodeURIComponent(TOKEN)}` : '';
53
+ if (!src) return all;
54
+ return `<a class="pic" href="${src}" target="_blank" rel="noopener noreferrer"><img src="${src}" alt="${alt}" loading="lazy" onerror="this.parentNode.classList.add('broken')"></a>`;
55
+ })
56
+ .replace(/(^|[^!])\[([^\]]+)\]\(([^)\s]+)\)/g, (all, pre, t, href) => pre + ((() => {
50
57
  if (/^[\w./-]+\.html?(#[\w-]*)?$/i.test(href)) return `<a href="#" data-page="${href}">${t}</a>`;
58
+ if (/^#[\w-]+$/.test(href)) return `<a href="#" class="ref" data-focus="${href.slice(1)}">${t}</a>`;
51
59
  if (/^https:\/\/[^\s"'<>]+$/i.test(href)) return `<a href="${href}" target="_blank" rel="noopener noreferrer">${t}</a>`;
52
60
  return t;
53
- });
61
+ })()));
54
62
  }
55
63
  function md(text) {
56
64
  const lines = esc(text).split('\n');
@@ -96,38 +104,33 @@
96
104
  setPanel(narrow() ? false : store.get('truemap.panel') !== 'closed', false);
97
105
  $('togglePanel').onclick = () => { const open = !panelOpen(); setPanel(open); if (open) input.focus(); };
98
106
 
99
- // ---------- annotate ----------
100
- function setAnnotate(on, { touched = false } = {}) {
101
- state.annotate = !!on;
102
- if (touched) { state.annotateTouched = true; store.set('truemap.annotate', on ? 'on' : 'off'); }
103
- $('annotate').setAttribute('aria-checked', String(state.annotate));
104
- toFrame({ type: 'annotate', on: state.annotate });
105
- }
106
- state.annotate = store.get('truemap.annotate') === 'on';
107
- $('annotate').setAttribute('aria-checked', String(state.annotate));
108
- $('annotate').onclick = () => setAnnotate(!state.annotate, { touched: true });
109
107
 
110
108
  // ---------- page switcher ----------
111
109
  const resultFor = (page) => state.check.results?.find((r) => r.page === page);
112
110
  const stateOf = (r) => (r?.counts?.broken ? 'broken' : r?.counts?.changed ? 'changed' : '');
113
111
  const titleOf = (p) => (p.page === 'index.html' && (!p.title || p.title === 'index') ? 'Blueprint' : p.title || p.page);
114
112
 
113
+ // Drafts are the record of what the agent explained, newest first; other pages after them.
114
+ const isDraft = (p) => /^drafts\//.test(p.page);
115
+ const draftNo = (p) => { const n = parseInt(p.page.slice(7), 10); return Number.isFinite(n) ? n : null; };
115
116
  function renderMenu() {
116
117
  const list = $('pages'); list.innerHTML = '';
117
118
  const q = $('filter').value.trim().toLowerCase();
118
119
  $('filter').hidden = state.pages.length <= 7;
119
- state.pages
120
- .filter((p) => !q || `${p.title} ${p.page}`.toLowerCase().includes(q))
121
- .forEach((p, i, arr) => {
122
- const st = stateOf(resultFor(p.page));
123
- const b = document.createElement('button');
124
- b.type = 'button'; b.className = 'page-item' + (p.page === state.page ? ' active' : ''); b.setAttribute('role', 'menuitem');
125
- b.innerHTML = `<span class="pi-text"><span class="pi-title">${esc(titleOf(p))}</span><span class="pi-file">${esc(p.page)}</span></span>${st ? `<span class="tri ${st}" title="${st === 'broken' ? 'Out of date' : 'Code changed'}"></span>` : ''}`;
126
- b.onclick = () => { closeMenu(); go(p.page); };
127
- list.appendChild(b);
128
- if (i === 0 && p.page === 'index.html' && arr.length > 1) list.insertAdjacentHTML('beforeend', '<div class="menu-gap"></div>');
129
- });
130
- if (!state.pages.length) list.innerHTML = '<div class="menu-head">No pages in .truemap/ yet</div>';
120
+ const match = (p) => !q || `${p.title} ${p.page}`.toLowerCase().includes(q);
121
+ const drafts = state.pages.filter((p) => isDraft(p) && match(p)).sort((a, b) => (draftNo(b) ?? 0) - (draftNo(a) ?? 0) || b.at - a.at);
122
+ const pages = state.pages.filter((p) => !isDraft(p) && p.page !== 'index.html' && match(p));
123
+ const item = (p, num) => {
124
+ const st = stateOf(resultFor(p.page));
125
+ const b = document.createElement('button');
126
+ b.type = 'button'; b.className = 'page-item' + (p.page === state.page ? ' active' : ''); b.setAttribute('role', 'menuitem');
127
+ b.innerHTML = `${num != null ? `<span class="pi-num">${num}</span>` : ''}<span class="pi-text"><span class="pi-title">${esc(titleOf(p))}</span><span class="pi-file">${p.at ? esc(timeOf(new Date(p.at).toISOString())) : esc(p.page)}</span></span>${st ? `<span class="tri ${st}" title="${st === 'broken' ? 'Out of date' : 'Code changed'}"></span>` : ''}`;
128
+ b.onclick = () => { closeMenu(); go(p.page); };
129
+ list.appendChild(b);
130
+ };
131
+ if (drafts.length) { list.insertAdjacentHTML('beforeend', '<div class="menu-label">Drafts</div>'); drafts.forEach((p) => item(p, draftNo(p))); }
132
+ if (pages.length) { list.insertAdjacentHTML('beforeend', '<div class="menu-label">Pages</div>'); pages.forEach((p) => item(p, null)); }
133
+ if (!drafts.length && !pages.length) list.innerHTML = `<div class="menu-head">${state.pages.length ? 'No drafts yet. Ask the agent to explain something and it draws one here.' : 'No pages in .truemap/ yet'}</div>`;
131
134
  }
132
135
  function openMenu() { renderMenu(); menu.hidden = false; $('pageBtn').setAttribute('aria-expanded', 'true'); ($('filter').hidden ? menu.querySelector('.page-item.active, .page-item') : $('filter'))?.focus(); }
133
136
  function closeMenu() { menu.hidden = true; $('pageBtn').setAttribute('aria-expanded', 'false'); }
@@ -139,14 +142,11 @@
139
142
  const typing = e.target.closest?.('input,textarea,select,[contenteditable]');
140
143
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
141
144
  else if (e.key === 'Escape' && !menu.hidden) { closeMenu(); $('pageBtn').focus(); }
142
- else if (e.key === 'Escape' && !typing && state.annotate && $('moreMenu').hidden) setAnnotate(false, { touched: true });
143
145
  else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
144
146
  const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
145
147
  e.preventDefault();
146
148
  const i = items.indexOf(document.activeElement);
147
149
  items[(i + (e.key === 'ArrowDown' ? 1 : -1) + items.length) % items.length].focus();
148
- } else if (!typing && !e.ctrlKey && !e.metaKey && !e.altKey && e.key.toLowerCase() === 'a' && menu.hidden) {
149
- setAnnotate(!state.annotate, { touched: true });
150
150
  }
151
151
  });
152
152
  $('recheck').onclick = () => { api('/api/check'); closeMenu(); };
@@ -168,6 +168,20 @@
168
168
  $('endHint').textContent = talking ? `Lets ${agentName()} go back to the terminal` : 'No conversation is running';
169
169
  }
170
170
  const closeMore = () => { more.hidden = true; $('moreBtn').setAttribute('aria-expanded', 'false'); };
171
+ const renderTheme = () => {
172
+ const t = document.documentElement.getAttribute('data-theme') || '';
173
+ for (const b of document.querySelectorAll('[data-theme-pick]')) b.setAttribute('aria-pressed', String(b.dataset.themePick === t));
174
+ };
175
+ renderTheme();
176
+ for (const b of document.querySelectorAll('[data-theme-pick]')) {
177
+ b.onclick = () => {
178
+ const t = b.dataset.themePick;
179
+ if (t) document.documentElement.setAttribute('data-theme', t); else document.documentElement.removeAttribute('data-theme');
180
+ renderTheme();
181
+ toFrame({ type: 'theme', theme: t });
182
+ api('/api/prefs', { theme: t || 'system' });
183
+ };
184
+ }
171
185
  $('moreBtn').onclick = (e) => {
172
186
  e.stopPropagation();
173
187
  if (!more.hidden) return closeMore();
@@ -188,20 +202,27 @@
188
202
 
189
203
  function renderHeader() {
190
204
  const p = state.pages.find((x) => x.page === state.page);
191
- $('pageTitle').textContent = p ? titleOf(p) : (state.pages.length ? 'Pages' : 'No pages yet');
192
- $('pagePath').textContent = state.page ? `.truemap/${state.page}` : '';
193
- document.title = p ? `${titleOf(p)} – truemap` : 'truemap';
205
+ // The map is always one click away; the switcher names the draft or page you are on, or offers the drafts.
206
+ const home = state.pages.find((x) => x.page === 'index.html');
207
+ const onMap = !state.page || state.page === 'index.html';
208
+ $('crumbHome').hidden = !home; $('crumbHome').classList.toggle('on', onMap);
209
+ const nDrafts = state.pages.filter(isDraft).length;
210
+ $('pageTitle').textContent = !onMap && p ? `${isDraft(p) && draftNo(p) != null ? `#${draftNo(p)} ` : ''}${titleOf(p)}` : nDrafts ? `Drafts (${nDrafts})` : state.pages.length > 1 ? 'Pages' : 'No drafts yet';
211
+ renderProjects();
194
212
  const r = resultFor(state.page); const st = stateOf(r);
195
213
  const chip = $('checkChip');
196
214
  if (!r || r.missing || !r.anchors?.length || state.conn === 'closed') { chip.hidden = true; return; }
197
- chip.hidden = false;
215
+ chip.hidden = !st;
198
216
  const { changed, broken } = r.counts;
199
217
  chip.dataset.state = st || 'ok';
200
218
  $('checkText').textContent = broken ? S.broken(broken) + (changed ? `, ${S.changed(changed)}` : '') : changed ? S.changed(changed) : S.ok;
201
- chip.title = st ? 'Ask the agent to update this page' : `${r.counts.ok} boxes checked against the code`;
219
+ chip.title = st ? 'Ask the agent to update this page' : `${S.ok}: ${r.counts.ok} boxes checked`;
220
+ if (!st) $('checkText').textContent = '';
221
+ chip.setAttribute('aria-label', st ? $('checkText').textContent : S.ok);
202
222
  }
203
223
  function sendMarks() {
204
224
  const r = resultFor(state.page);
225
+ if (panelEl.classList.contains('show-changes')) return toFrame({ type: 'marks', items: [] });
205
226
  toFrame({ type: 'marks', items: (r?.anchors || []).filter((a) => a.state !== 'ok').map((a) => ({ src: a.src, state: a.state })) });
206
227
  }
207
228
 
@@ -212,23 +233,27 @@
212
233
  if (state.page !== page || force) frame.src = pageUrl(page);
213
234
  setCurrent(page);
214
235
  }
236
+ // Back and forward between pages, like a browser (Alt+Left / Alt+Right, mouse side buttons).
237
+ const nav = { back: [], fwd: [], moving: false };
215
238
  function setCurrent(page) {
239
+ if (state.page && page !== state.page && !nav.moving) { nav.back.push(state.page); nav.fwd = []; if (nav.back.length > 50) nav.back.shift(); }
240
+ nav.moving = false;
216
241
  state.page = page;
217
242
  history.replaceState(null, '', `${location.pathname}${location.search}#page=${encodeURIComponent(page)}`);
218
243
  api('/api/viewing', { page });
219
- renderHeader(); renderNotice(); renderNotes();
244
+ renderHeader(); renderNotice(); renderNotes(); renderNav();
220
245
  }
221
246
  function showEmpty() {
222
247
  state.page = null; frame.hidden = true; frame.removeAttribute('src'); $('empty').hidden = false; renderHeader(); renderNotice();
223
248
  }
224
249
  const reloadFrame = () => { if (state.page) frame.src = pageUrl(state.page, true); };
225
250
 
226
- // ---------- notes (comments collected in annotate mode) ----------
251
+ // ---------- notes: comments on boxes or text, sent together ----------
227
252
  const notesForPage = () => state.notes.filter((n) => n.page === state.page);
228
253
  function syncFrameNotes() { toFrame({ type: 'notes', items: notesForPage().map(({ id, kind, label, src, text, selector, rect }) => ({ id, kind, label, src, text, selector, rect })) }); }
229
254
  // Unsent comments survive a reload of this tab.
230
- try { state.notes = JSON.parse(sessionStorage.getItem('truemap.notes') || '[]'); } catch { state.notes = []; }
231
- function saveNotes() { try { sessionStorage.setItem('truemap.notes', JSON.stringify(state.notes)); } catch { /* ignore */ } }
255
+ try { state.notes = JSON.parse(localStorage.getItem('truemap.notes') || '[]'); } catch { state.notes = []; }
256
+ function saveNotes() { try { localStorage.setItem('truemap.notes', JSON.stringify(state.notes)); } catch { /* ignore */ } }
232
257
  function renderNotes() {
233
258
  saveNotes(); renderBadge();
234
259
  const list = $('notes'); list.innerHTML = '';
@@ -241,13 +266,17 @@
241
266
  list.appendChild(li);
242
267
  });
243
268
  const count = state.notes.length;
244
- $('send').textContent = count ? `Send ${count} comment${count > 1 ? 's' : ''}` : 'Send';
245
- input.placeholder = count ? S.placeholderNotes : S.placeholder;
269
+ const reviewing = state.plan?.status === 'review' && state.plan.page === state.page;
270
+ $('send').textContent = planRequest ? 'Send request' : reviewing && count ? 'Send' : count ? `Send ${count} comment${count > 1 ? 's' : ''}` : 'Send';
271
+ const rq = planBar.querySelector('[data-pb="request"]');
272
+ if (rq) { rq.textContent = count && reviewing ? `Request changes (${count})` : 'Request changes'; rq.classList.toggle('primary', !!(count && reviewing)); planBar.querySelector('[data-pb="approve"]')?.classList.toggle('primary', !(count && reviewing)); }
273
+ $('send').classList.toggle('quiet', !!(reviewing && count));
274
+ if (!planRequest) input.placeholder = count ? S.placeholderNotes : S.placeholder;
246
275
  }
247
276
 
248
277
  // ---------- conversation ----------
249
278
  function whoLine(role, at, name) {
250
- const el = document.createElement('div'); el.className = 'who';
279
+ const el = document.createElement('div'); el.className = role === 'agent' ? 'who' : 'who you';
251
280
  el.innerHTML = `<b>${esc(role === 'agent' ? (AGENTS[name] || name || agentName()) : S.you)}</b><span>${timeOf(at)}</span>`;
252
281
  return el;
253
282
  }
@@ -255,23 +284,47 @@
255
284
  function renderAll() {
256
285
  msgsEl.innerHTML = ''; lastRole = null;
257
286
  if (!state.history.length) {
258
- msgsEl.innerHTML = `<div class="intro"><h2>Ask about anything on the page</h2><ol>
259
- <li>Turn on <b>Annotate</b> (or press <kbd>A</kbd>), then click a box or select text to comment on it.</li>
260
- <li>Add as many comments as you like. They go out together, each with the code it points to.</li>
261
- <li>Or just type a question below.</li></ol></div>`;
287
+ msgsEl.innerHTML = `<div class="intro"><p>Ask about anything on the page. <b>Click a box</b> to see what it is; <b>double-click</b> it to write a comment right there. Comments go out together, each with the code it points to.</p></div>`;
262
288
  }
263
289
  for (const e of state.history) appendEntry(e, false);
264
290
  renderWorking();
265
- scrollChat();
291
+ scrollChat(); requestAnimationFrame(scrollChat); setTimeout(scrollChat, 300);
292
+ }
293
+ // What changed in a turn: one card in the conversation, badges on the map, the diff from the box.
294
+ function changesCard(c) {
295
+ const d = (a, x) => `<span class="delta">${[a ? `<span class="a">+${a}</span>` : '', x ? `<span class="d">−${x}</span>` : ''].filter(Boolean).join(' ') || '±0'}</span>`;
296
+ const rows = c.boxes.map((b) => `<button type="button" class="cc-row" data-src="${esc(b.src)}" data-page="${esc(b.pages?.includes(state.page) ? state.page : (b.pages?.[0] || state.page))}"><b>${esc(b.name || b.src.split('#')[1] || b.src)}${b.isNew ? '<span class="cc-new">New</span>' : ''}</b>${d(b.add, b.del)}</button>`).join('');
297
+ const loose = c.unmapped?.length ? `<details class="cc-loose"><summary>${c.unmapped.length} file${c.unmapped.length > 1 ? 's' : ''} not on the map</summary>${c.unmapped.map((x) => `<div><code>${esc(x.path)}</code>${d(x.add, x.del)}</div>`).join('')}<button type="button" class="text-btn" data-act="map-these">Ask the agent to map these</button></details>` : '';
298
+ const notDone = c.notDone?.length ? `<p class="cc-warn">Planned, no changes: ${esc(c.notDone.join(', '))}</p>` : '';
299
+ return `<div class="cc"><div class="cc-head"><b>Changed ${c.files} file${c.files > 1 ? 's' : ''}</b>${d(c.add, c.del)}</div>${rows ? `<div class="cc-rows">${rows}</div>` : ''}${notDone}${loose}<p class="cc-hint">Click a box to see its diff.</p></div>`;
300
+ }
301
+ let latestChanges = null;
302
+ function showChangeBadges() {
303
+ toFrame({ type: 'changes', on: false, items: latestChanges ? latestChanges.boxes.filter((b) => !b.pages || b.pages.includes(state.page)).map((b) => ({ src: b.src, add: b.add, del: b.del, isNew: !!b.isNew })) : [] });
266
304
  }
267
305
  function appendEntry(e, scroll = true, live = false) {
268
306
  msgsEl.querySelector('.intro')?.remove();
269
307
  if (e.role !== lastRole) { msgsEl.appendChild(whoLine(e.role, e.at, e.agent)); lastRole = e.role; }
270
308
  const el = document.createElement('div');
309
+ if (e.kind === 'changes' && e.changes) {
310
+ el.className = 'msg agent';
311
+ el.innerHTML = changesCard(e.changes);
312
+ latestChanges = e.changes; showChangeBadges();
313
+ msgsEl.appendChild(el); renderWorking(); if (scroll) scrollChat();
314
+ if (live && !panelOpen()) { state.unread = true; renderBadge(); }
315
+ return;
316
+ }
271
317
  if (e.role === 'agent') {
272
318
  el.className = 'msg agent';
273
- el.innerHTML = md(e.text);
319
+ el.innerHTML = e.ask && e.text.trim() === e.ask.question.trim() ? '' : md(e.text);
320
+ for (const li of el.querySelectorAll('li')) if (li.querySelector('a.ref')) li.classList.add('has-ref');
321
+ if (e.focus?.length) {
322
+ if (!e.plan) el.insertAdjacentHTML('beforeend', `<p class="show-map"><a href="#" data-focus="${esc(e.focus.join(','))}">Show on the map</a></p>`);
323
+ if (live) pointAt(e.focus, '', AGENTS[e.agent] || agentName());
324
+ }
325
+ if (e.ask) el.appendChild(askCard(e));
274
326
  if (live && !panelOpen()) { state.unread = true; renderBadge(); }
327
+ if (live && panelEl.classList.contains('inspecting')) $('inspBack').classList.add('news');
275
328
  } else {
276
329
  el.className = 'msg user'; el.dataset.id = e.id;
277
330
  let body = '';
@@ -295,13 +348,175 @@
295
348
  if (scroll) scrollChat();
296
349
  }
297
350
  const scrollChat = () => { msgsEl.scrollTop = msgsEl.scrollHeight; };
351
+ let hoverLit = null;
352
+ msgsEl.addEventListener('mouseover', (e) => {
353
+ const host = e.target.closest('li.has-ref, a.ref');
354
+ const ids = host ? [...new Set([...(host.matches('a.ref') ? [host] : host.querySelectorAll('a.ref'))].flatMap((r) => r.dataset.focus.split(',')).filter(Boolean))] : null;
355
+ const key = ids ? ids.join(',') : null;
356
+ if (key === hoverLit || (!key && (hoverLit === '__pinned' || !hoverLit))) return;
357
+ msgsEl.querySelector('li.lit')?.classList.remove('lit');
358
+ hoverLit = key;
359
+ if (ids) { if (host.matches('li')) host.classList.add('lit'); toFrame({ type: 'focus', items: ids, note: '', who: '', scroll: false, transient: true }); }
360
+ else toFrame({ type: 'clear-focus' });
361
+ });
362
+ msgsEl.addEventListener('mouseleave', () => { if (hoverLit && hoverLit !== '__pinned') { hoverLit = null; msgsEl.querySelector('li.lit')?.classList.remove('lit'); toFrame({ type: 'clear-focus' }); } });
298
363
  msgsEl.addEventListener('click', (e) => {
364
+ const cc = e.target.closest('.cc-row');
365
+ if (cc) { if (cc.dataset.page !== state.page) { state.pendingOpen = cc.dataset.src; go(cc.dataset.page); } else toFrame({ type: 'open-box', src: cc.dataset.src }); return; }
366
+ if (e.target.closest('[data-act="map-these"]')) {
367
+ const files = [...e.target.closest('.cc').querySelectorAll('.cc-loose code')].map((c) => c.textContent);
368
+ send(`These changed files are not on the map yet. Add boxes for the ones that matter (or say why they don't need one): ${files.join(', ')}`, { context: [], noNotes: true });
369
+ return;
370
+ }
371
+ const ref = e.target.closest('[data-focus]');
372
+ if (ref) { e.preventDefault(); hoverLit = '__pinned'; pointAt(ref.dataset.focus.split(',').filter(Boolean), '', ''); return; }
373
+ const step = e.target.closest('li.has-ref');
374
+ if (step) { hoverLit = '__pinned'; pointAt([...step.querySelectorAll('a.ref')].flatMap((r) => r.dataset.focus.split(',')).filter(Boolean), '', ''); return; }
375
+ const opt = e.target.closest('.ask-opt');
376
+ if (opt && !opt.disabled) { e.preventDefault(); answerAsk(opt); return; }
299
377
  const a = e.target.closest('a[data-page]');
300
378
  if (!a) return;
301
379
  e.preventDefault();
302
- const [page] = a.dataset.page.split('#');
303
- if (state.pages.some((p) => p.page === page)) go(page);
380
+ const [page, id] = a.dataset.page.split('#');
381
+ if (state.pages.some((p) => p.page === page)) { if (id) state.pendingFocus = { items: [id] }; go(page); }
304
382
  });
383
+
384
+ // ---------- the agent points at the map ----------
385
+ function pointAt(items, note, who, page) {
386
+ const target = page && state.pages.some((p) => p.page === page) ? page : state.page;
387
+ const msg = { type: 'focus', items, note: note || '', who: who || agentName() };
388
+ if (target && target !== state.page) { state.pendingFocus = msg; go(target); } else toFrame(msg);
389
+ }
390
+
391
+ // ---------- choices the agent asks for (only when it is blocked on a real trade-off) ----------
392
+ function askCard(e) {
393
+ const answered = state.history.find((h) => h.kind === 'answer' && h.answer?.question === e.ask.question && h.at > e.at)
394
+ || state.history.some((h) => h.role === 'agent' && h.ask && h.at > e.at); // a later question replaced this one
395
+ const box = document.createElement('div'); box.className = 'ask';
396
+ box.innerHTML = `<div class="ask-q">${esc(e.ask.question)}</div>` + e.ask.options.map((o, i) =>
397
+ `<button type="button" class="ask-opt${answered?.answer?.choice === o.label ? ' chosen' : ''}" data-i="${i}" ${answered ? 'disabled' : ''}><b>${esc(o.label)}</b>${o.why ? `<span>${esc(o.why)}</span>` : ''}</button>`).join('');
398
+ box.dataset.q = e.ask.question;
399
+ return box;
400
+ }
401
+ function answerAsk(btn) {
402
+ const box = btn.closest('.ask');
403
+ for (const b of box.querySelectorAll('.ask-opt')) b.disabled = true;
404
+ btn.classList.add('chosen');
405
+ send('', { kind: 'answer', noNotes: true, context: [], answer: { question: box.dataset.q, choice: btn.querySelector('b').textContent, note: '' } });
406
+ }
407
+
408
+ // ---------- inspector: what a box is. It takes the panel's place until you go back. ----------
409
+ const panelEl = $('panel'); const inspBody = $('inspBody');
410
+ const pageHref = (href) => {
411
+ const [file, id] = href.split('#');
412
+ const base = state.page && state.page.includes('/') ? state.page.replace(/[^/]+$/, '') : '';
413
+ const parts = (base + file).split('/'); const outp = [];
414
+ for (const p of parts) { if (p === '..') outp.pop(); else if (p && p !== '.') outp.push(p); }
415
+ return { page: outp.join('/'), id };
416
+ };
417
+ const PLAN = { new: 'New in this plan', change: 'Changes in this plan', remove: 'Removed in this plan' };
418
+ let inspSeq = 0; let panelWasClosed = false;
419
+ const inspecting = () => panelEl.classList.contains('inspecting');
420
+ function closeInspector() {
421
+ if (!inspecting()) return;
422
+ panelEl.classList.remove('inspecting'); inspBody.innerHTML = ''; inspSeq++; app.classList.remove('wide-panel'); $('inspBack').classList.remove('news'); scrollChat();
423
+ toFrame({ type: 'select', id: null });
424
+ if (panelWasClosed) { panelWasClosed = false; setPanel(false, false); }
425
+ }
426
+ $('inspBack').onclick = () => closeInspector();
427
+ const absPath = (rel) => { const sep = String(state.root).includes('\\') ? '\\' : '/'; return [state.root, ...rel.split('/')].join(sep); };
428
+ async function loadCode(box, holder, seq) {
429
+ let sn = {};
430
+ try { sn = await fetch(`/api/snippet?src=${encodeURIComponent(box.src)}&t=${encodeURIComponent(TOKEN)}`).then((r) => r.json()); } catch { sn = { error: 'Could not read the code' }; }
431
+ if (seq !== inspSeq) return; // another box was opened meanwhile
432
+ if (sn.kind === 'folder') holder.innerHTML = `<div class="code-note">A folder: ${esc(sn.path)}</div>`;
433
+ else if (sn.error) holder.innerHTML = `<div class="code-note">${esc(sn.error)}</div>`;
434
+ else if (sn.missing) holder.innerHTML = `<div class="code-note broken">“${esc(sn.name)}” no longer appears in ${esc(sn.path)}. The code moved on; ask the agent to update this box.</div>`;
435
+ else {
436
+ holder.innerHTML = `<div class="code-meta">Line ${sn.line}${sn.lastChange ? `, changed ${esc(sn.lastChange)}` : ''}</div><pre>${sn.lines.map((l, i) => `<span class="${sn.start + i === sn.line ? 'hit' : ''}"><i>${sn.start + i}</i>${esc(l) || ' '}</span>`).join('')}</pre>`;
437
+ const ed = inspBody.querySelector('.open-ed');
438
+ if (ed) { ed.href = `vscode://file/${absPath(sn.path).replace(/\\/g, '/')}:${sn.line}`; ed.hidden = false; }
439
+ const hit = holder.querySelector('.hit'); const pre = holder.querySelector('pre');
440
+ if (hit && pre) pre.scrollTop = Math.max(0, hit.offsetTop - pre.offsetTop - 44);
441
+ holder.closest('.insp-code')?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
442
+ }
443
+ }
444
+ function openInspector(box) {
445
+ const seq = ++inspSeq;
446
+ if (!panelOpen()) { panelWasClosed = true; setPanel(true, false); }
447
+ panelEl.classList.add('inspecting');
448
+ $('inspBack').lastChild.textContent = panelEl.classList.contains('show-changes') ? 'Changes' : 'Conversation';
449
+ toFrame({ type: 'select', id: box.id || null, src: box.src || '' });
450
+ const chips = (list) => list.map((c) => `<button type="button" class="chip" data-box="${esc(c.id)}">${esc(c.label)}${c.via ? `<i>${esc(c.via)}</i>` : ''}</button>`).join('');
451
+ const page = box.href ? pageHref(box.href) : null;
452
+ const pageT = page && state.pages.find((p) => p.page === page.page);
453
+ let detail = ''; let list = false;
454
+ for (const d of box.detail || []) {
455
+ if (d.t === 'li' && !list) { detail += '<ul>'; list = true; }
456
+ if (d.t !== 'li' && list) { detail += '</ul>'; list = false; }
457
+ detail += d.t === 'li' ? `<li>${esc(d.text)}</li>` : `<p>${esc(d.text)}</p>`;
458
+ }
459
+ if (list) detail += '</ul>';
460
+ if (!detail && box.desc) detail = `<p>${esc(box.desc)}</p>`;
461
+ const rel = box.to.length || box.from.length;
462
+ inspBody.innerHTML = `
463
+ <div class="insp-name"><h2>${esc(box.label)}</h2>${box.tag ? `<code>${esc(box.tag)}</code>` : ''}</div>
464
+ ${PLAN[box.plan] ? `<span class="insp-plan">${PLAN[box.plan]}</span>${box.planNote ? `<p class="insp-why">${esc(box.planNote)}</p>` : ''}` : ''}
465
+ ${box.mark && !(box.mark === 'changed' && latestChanges?.boxes?.some((x) => x.src === box.src)) ? `<div class="insp-state ${box.mark === 'broken' ? 'broken' : ''}">${box.mark === 'broken' ? 'This box no longer matches the code.' : 'The code changed since this box was last checked.'}</div>` : ''}
466
+ ${box.mark === 'changed' && box.src && !latestChanges?.boxes?.some((x) => x.src === box.src) ? '<details class="insp-drift" open><summary>What changed in its code</summary><div class="code-box"><div class="code-note">Reading the diff…</div></div></details>' : ''}
467
+ ${unbuiltNote(box)}${changeSection(box)}
468
+ ${detail ? `<div class="insp-detail">${detail}</div>` : ''}
469
+ ${box.why ? `<div class="insp-why">${esc(box.why)}</div>` : ''}
470
+ <form class="insp-comment"><textarea rows="1" aria-label="Comment"></textarea><button type="submit" disabled>Add</button></form>
471
+ ${rel ? `<div class="insp-rel">${box.to.length ? `<span>Calls</span><div>${chips(box.to)}</div>` : ''}${box.from.length ? `<span>Called by</span><div>${chips(box.from)}</div>` : ''}</div>` : ''}
472
+ ${box.src ? `<details class="insp-code"><summary><svg viewBox="0 0 16 16" aria-hidden="true"><path d="M6 3.5 10.5 8 6 12.5"/></svg>Code <code>${esc(box.src.split('#')[0])}</code><a class="open-ed" hidden>Open in VS Code</a></summary><div class="code-box"><div class="code-note">Reading the code…</div></div></details>`
473
+ : box.ext ? '<div class="insp-why">Outside this code base.</div>' : ''}
474
+ ${pageT ? `<div class="insp-actions">${pageT ? `<button type="button" data-act="open">Open ${esc(titleOf(pageT))}</button>` : ''}</div>` : ''}`;
475
+ inspBody.scrollTop = 0;
476
+ wireChangeSection();
477
+ const drift = inspBody.querySelector('.insp-drift .code-box');
478
+ if (drift) {
479
+ const a = resultFor(state.page)?.anchors?.find((x) => x.src === box.src);
480
+ fetch(`/api/drift?path=${encodeURIComponent(box.src.split('#')[0].replace(/\/+$/, ''))}&since=${encodeURIComponent(a?.since || '')}&t=${encodeURIComponent(TOKEN)}`).then((r) => r.json())
481
+ .then((r) => { if (seq === inspSeq) drift.innerHTML = r.error ? `<div class="code-note">${esc(r.error)}</div>` : r.text.trim() ? diffHtml(r.text) : '<div class="code-note">No text changes since then (only the file time moved).</div>'; })
482
+ .catch(() => { drift.innerHTML = '<div class="code-note">Could not read the diff.</div>'; });
483
+ }
484
+ const form = inspBody.querySelector('.insp-comment'); const ta = form.querySelector('textarea'); const add = form.querySelector('button');
485
+ ta.placeholder = `Comment on ${box.label}, or ask about it`;
486
+ ta.addEventListener('input', () => { add.disabled = !ta.value.trim(); ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 140) + 'px'; });
487
+ ta.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); form.requestSubmit(); } });
488
+ form.onsubmit = (e) => {
489
+ e.preventDefault();
490
+ const text = ta.value.trim(); if (!text) return;
491
+ state.notes.push({ id: `n${Date.now().toString(36)}`, page: state.page, kind: 'element', label: box.label, src: box.src || '', excerpt: (box.detail?.[0]?.text || box.desc || '').slice(0, 400), text, selector: box.id ? `#${CSS.escape(box.id)}` : '', rect: null });
492
+ renderNotes(); syncFrameNotes();
493
+ panelWasClosed = false; closeInspector(); input.focus();
494
+ };
495
+ const code = inspBody.querySelector('.insp-code');
496
+ if (code) code.addEventListener('toggle', () => { if (code.open && !code.dataset.loaded) { code.dataset.loaded = '1'; loadCode(box, code.querySelector('.code-box'), seq); } });
497
+ inspBody.querySelector('.open-ed')?.addEventListener('click', (e) => e.stopPropagation());
498
+ inspBody.onclick = (ev) => {
499
+ const chip = ev.target.closest('[data-box]');
500
+ if (chip) { toFrame({ type: 'open-box', id: chip.dataset.box }); return; }
501
+ const act = ev.target.closest('[data-act]')?.dataset.act;
502
+ if (act === 'open') { closeInspector(); if (page.id) state.pendingFocus = { type: 'focus', items: [page.id] }; go(page.page); }
503
+ else if (act === 'links') pointAt([box.id, ...box.to.map((c) => c.id), ...box.from.map((c) => c.id)], '', '');
504
+ };
505
+ }
506
+ document.addEventListener('keydown', (e) => {
507
+ if (e.key !== 'Escape' || !inspecting() || !menu.hidden || !$('moreMenu').hidden) return;
508
+ if (e.target.closest?.('.insp-comment') && e.target.value) return;
509
+ closeInspector(); toFrame({ type: 'clear-focus' }); e.stopPropagation();
510
+ }, true);
511
+
512
+ // "Ask about this": the box goes along with the next message.
513
+ function renderAbout() {
514
+ const el = $('about'); const a = state.about;
515
+ el.hidden = !a; if (!a) { el.innerHTML = ''; return; }
516
+ el.innerHTML = `<span>About <b>${esc(a.label)}</b>${a.src ? ` <code>${esc(a.src)}</code>` : ''}</span><button type="button" aria-label="Remove">×</button>`;
517
+ el.querySelector('button').onclick = () => { state.about = null; renderAbout(); };
518
+ input.placeholder = `Ask about ${a.label}`;
519
+ }
305
520
  function markPending(id, on) {
306
521
  const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(id)}"]`);
307
522
  if (!el) return;
@@ -309,6 +524,242 @@
309
524
  if (on) el.insertAdjacentHTML('beforeend', `<div class="waiting">${S.waiting}</div>`);
310
525
  }
311
526
 
527
+ // ---------- changes: what changed since a base, by box ----------
528
+ const tabs = { convo: $('tabConvo'), changes: $('tabChanges') };
529
+ const BASES = { turn: 'Since the agent’s last turn began', plan: 'Since you approved the plan', head: 'Uncommitted changes', main: 'This branch vs main' };
530
+ const ch = { base: store.get('truemap.base') || 'auto', data: null, names: new Map() };
531
+ const showingChanges = () => panelEl.classList.contains('show-changes');
532
+ function setTab(which) {
533
+ panelEl.classList.toggle('show-changes', which === 'changes');
534
+ tabs.convo.setAttribute('aria-selected', String(which !== 'changes'));
535
+ tabs.changes.setAttribute('aria-selected', String(which === 'changes'));
536
+ closeInspector();
537
+ if (which === 'changes') { renderChanges(); loadChanges(); }
538
+ sendChangeMarks(); sendMarks();
539
+ }
540
+ tabs.convo.onclick = () => setTab('convo');
541
+ tabs.changes.onclick = () => setTab('changes');
542
+ let loadingChanges = false;
543
+ async function loadChanges() {
544
+ if (state.conn !== 'live' || loadingChanges) return;
545
+ loadingChanges = true;
546
+ let r = null;
547
+ try { r = await fetch(`/api/changes?base=${encodeURIComponent(ch.base)}&t=${encodeURIComponent(TOKEN)}`).then((x) => x.json()); } catch { r = null; }
548
+ loadingChanges = false;
549
+ if (!r) return;
550
+ ch.data = r;
551
+ const n = r.error ? 0 : r.files;
552
+ $('changesCount').hidden = !n; $('changesCount').textContent = n ? String(n) : '';
553
+ if (showingChanges()) renderChanges();
554
+ sendChangeMarks();
555
+ }
556
+ function sendChangeMarks() {
557
+ const on = showingChanges() && ch.data && !ch.data.error;
558
+ toFrame({
559
+ type: 'changes', on: !!on, items: on ? ch.data.boxes.filter((b) => b.pages.includes(state.page)).map((b) => ({ src: b.src, add: b.add, del: b.del })) : [],
560
+ unbuilt: on && ch.data.plan ? ch.data.plan.planned.filter((p) => !p.changed).map((p) => ({ box: p.box, src: p.src, what: p.what })) : [],
561
+ });
562
+ }
563
+ const delta = (a, d) => `<span class="delta">${a == null ? 'binary' : [a ? `<span class="a">+${a}</span>` : '', d ? `<span class="d">−${d}</span>` : ''].filter(Boolean).join(' ') || '±0'}</span>`;
564
+ const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
565
+ function renderChanges() {
566
+ const el = $('changes'); const r = ch.data;
567
+ if (!r) { el.innerHTML = '<p class="ch-empty">Reading the working tree…</p>'; return; }
568
+ if (r.error) { el.innerHTML = `<p class="ch-empty">Changes need a git repository with at least one commit (${esc(r.error)}).</p>`; return; }
569
+ const opts = r.bases.map((k) => `<option value="${k}"${k === r.base.kind ? ' selected' : ''}>${esc(k === r.base.kind ? r.base.label : BASES[k])}</option>`).join('');
570
+ const WHY = { turn: 'What the agent changed since it picked up your last message.', plan: r.base.label.startsWith('What was done') ? 'What was changed between your approval and the end of the plan.' : 'What changed since you approved the plan.', head: 'Everything not committed yet, yours and the agent’s.', main: 'Everything on this branch that main doesn’t have, like a pull request.' };
571
+ let html = `<div class="ch-base"><select id="chBase" aria-label="Compare with">${opts}</select><span class="ch-sum">${r.files ? `${plural(r.files, 'file')} ${delta(r.add, r.del)}` : 'Nothing changed'}</span></div><p class="ch-why">${esc(WHY[r.base.kind] || '')} Click a changed box to see its diff.</p>`;
572
+ if (r.plan) {
573
+ const done = r.plan.planned.filter((p) => p.changed).length; const missing = r.plan.planned.filter((p) => !p.changed);
574
+ html += `<div class="ch-plan"><div class="ch-h">Plan: ${esc(r.plan.title)}</div><p class="ch-sum">${done} of ${r.plan.planned.length} planned boxes have changes${r.plan.unplanned.length ? `, ${plural(r.plan.unplanned.length, 'box')} outside the plan` : ''}. Open a box to check its diff against what was planned.</p>`;
575
+ const STEP = { done: 'Agent: done', partly: 'Agent: partly done', not_built: 'Agent: not built', dropped: 'Agent: dropped' };
576
+ const conflicts = (r.plan.steps || []).filter((st) => st.conflict || st.rewritten);
577
+ if (conflicts.length) html += `<div class="ch-conflicts"><b>Check these before you trust the report</b>${conflicts.map((st) => `<p>Step ${st.n}: ${esc([st.conflict, st.rewritten].filter(Boolean).join(' '))}</p>`).join('')}</div>`;
578
+ if (r.plan.steps?.length) {
579
+ html += `<ol class="ch-steps">${r.plan.steps.map((st) => {
580
+ const quiet = [...st.files.filter((x) => !x.changed).map((x) => x.path), ...st.boxes.filter((x) => !x.changed).map((x) => x.name)];
581
+ const rp = st.report ? `<span class="st-rep st-${esc(st.report.status)}">${STEP[st.report.status] || esc(st.report.status)}${st.report.note ? `: ${esc(st.report.note)}` : ''}</span>` : `<span class="st-rep">${r.plan.status === 'done' ? 'Agent: not reported' : 'Not reported yet'}</span>`;
582
+ return `<li class="${st.conflict ? 'st-conflict' : ''}"><span class="st-text">${inline(esc(st.text.replace(/\[([^\]]+)\]\(#[\w-]+\)/g, '$1')))}</span>${rp}${quiet.length ? `<span class="st-fact">Names ${esc(quiet.join(', '))}, which ${quiet.length > 1 ? 'have' : 'has'} no changes</span>` : ''}</li>`;
583
+ }).join('')}</ol>`;
584
+ }
585
+ if (missing.length) html += `<ul class="ch-missing">${missing.map((p) => `<li><b>${esc(p.name || ch.names.get(p.src) || p.box)}</b> planned, no changes in its files${p.what ? `<small>${esc(p.what)}</small>` : ''}</li>`).join('')}</ul>`;
586
+ html += '</div>';
587
+ }
588
+ const planned = new Set((r.plan?.planned || []).map((p) => p.src).filter(Boolean));
589
+ if (r.boxes.length) {
590
+ html += '<div class="ch-h">On the map</div>';
591
+ for (const b of r.boxes) {
592
+ const here = b.pages.includes(state.page);
593
+ const name = ch.names.get(b.src) || b.src.split('#')[1] || b.src.split('/').pop();
594
+ const other = here ? '' : `, on ${titleOf(state.pages.find((p) => p.page === b.pages[0]) || { page: b.pages[0] })}`;
595
+ const offPlan = r.plan && !planned.has(b.src) ? '<span class="off-plan">not in the plan</span>' : '';
596
+ const want = r.plan?.planned.find((p) => p.src === b.src)?.what;
597
+ html += `<button type="button" class="ch-row" data-src="${esc(b.src)}" data-page="${esc(here ? state.page : b.pages[0])}"><b>${esc(name)}${offPlan}</b>${delta(b.add, b.del)}<small>${esc(b.files.map((f) => f.path).join(', ') + other)}</small>${want ? `<span class="ch-want">Planned: ${esc(want)}</span>` : ''}</button>`;
598
+ }
599
+ }
600
+ if (r.unmapped.length) {
601
+ const n = r.unmapped.reduce((k, g) => k + g.files.length, 0);
602
+ html += `<div class="ch-h">Not on the map: ${plural(n, 'file')}</div>`;
603
+ for (const g of r.unmapped) {
604
+ const nameOfSrc = (src) => ch.names.get(src) || src.split('#')[1] || src.split('/').pop();
605
+ html += `<details class="ch-folder"${n <= 6 ? ' open' : ''}><summary><b>${esc(g.folder)}</b><span>${plural(g.files.length, 'file')}</span></summary>${g.files.map((f) => `<button type="button" class="ch-file" data-path="${esc(f.path)}"><span>${esc(f.path)}${f.near ? `<em>next to ${esc(f.near.map(nameOfSrc).join(', '))}</em>` : ''}</span>${delta(f.add, f.del)}</button>`).join('')}</details>`;
606
+ }
607
+ html += '<div class="ch-act"><button type="button" data-act="map">Ask the agent to map these</button></div>';
608
+ }
609
+ if (!r.files) html += r.base.kind !== 'head' ? '<div class="ch-act"><button type="button" data-act="head">Show uncommitted changes instead</button></div>' : '<p class="ch-empty">It updates by itself while the agent works.</p>';
610
+ el.innerHTML = html;
611
+ }
612
+ function diffHtml(text) {
613
+ const rows = []; let oldN = 0; let newN = 0;
614
+ for (const l of String(text || '').split('\n')) {
615
+ if (/^(diff --git|index |--- |\+\+\+ |new file|deleted file|similarity|rename |\\ No newline)/.test(l)) continue;
616
+ const h = l.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)/);
617
+ if (h) { oldN = +h[1]; newN = +h[2]; rows.push(`<span class="hunk"><i></i>${esc(l.replace(/^@@[^@]*@@\s?/, '') || '…')}</span>`); continue; }
618
+ if (!l && !rows.length) continue;
619
+ const cls = l[0] === '+' ? 'add' : l[0] === '-' ? 'del' : '';
620
+ const n = cls === 'del' ? oldN++ : newN++; if (cls === '') oldN++;
621
+ rows.push(`<span class="${cls}"><i>${n}</i><em>${cls === 'add' ? '+' : cls === 'del' ? '−' : ' '}</em>${esc(l.slice(1)) || ' '}</span>`);
622
+ }
623
+ return rows.length ? `<pre>${rows.join('')}</pre>` : '<div class="code-note">No text changes (binary or mode only).</div>';
624
+ }
625
+ async function loadDiff(path, holder) {
626
+ holder.innerHTML = '<div class="code-note">Reading the diff…</div>';
627
+ let r = {};
628
+ try { r = await fetch(`/api/diff?base=${encodeURIComponent(ch.data?.base?.kind || ch.base)}&path=${encodeURIComponent(path)}&t=${encodeURIComponent(TOKEN)}`).then((x) => x.json()); } catch { r = { error: 'Could not read the diff' }; }
629
+ holder.innerHTML = r.error ? `<div class="code-note">${esc(r.error)}</div>` : diffHtml(r.text);
630
+ }
631
+ $('changes').addEventListener('change', (e) => {
632
+ if (e.target.id !== 'chBase') return;
633
+ ch.base = e.target.value; ch.userBase = true; store.set('truemap.base', ch.base); ch.data = null; renderChanges(); loadChanges();
634
+ });
635
+ $('changes').addEventListener('click', (e) => {
636
+ const row = e.target.closest('.ch-row');
637
+ if (row) {
638
+ if (row.dataset.page !== state.page) { state.pendingOpen = row.dataset.src; go(row.dataset.page); } else toFrame({ type: 'open-box', src: row.dataset.src });
639
+ return;
640
+ }
641
+ const file = e.target.closest('.ch-file');
642
+ if (file) {
643
+ const next = file.nextElementSibling;
644
+ if (next?.classList.contains('ch-diff')) { next.remove(); return; }
645
+ const box = document.createElement('div'); box.className = 'ch-diff code-box'; file.after(box); loadDiff(file.dataset.path, box);
646
+ return;
647
+ }
648
+ if (e.target.closest('[data-act="head"]')) { ch.base = 'head'; store.set('truemap.base', 'head'); ch.data = null; renderChanges(); loadChanges(); return; }
649
+ if (e.target.closest('[data-act="map"]')) {
650
+ const files = ch.data.unmapped.flatMap((g) => g.files.map((f) => f.path));
651
+ setTab('convo');
652
+ send(`These changed files are not on any page yet. Add boxes for the ones that matter (or say why they don't need one): ${files.slice(0, 40).join(', ')}${files.length > 40 ? ', …' : ''}`, { context: [], noNotes: true });
653
+ }
654
+ });
655
+ function unbuiltNote(box) {
656
+ if (!showingChanges() || !ch.data?.plan) return '';
657
+ const p = ch.data.plan.planned.find((x) => (x.src && x.src === box.src) || x.box === box.id);
658
+ if (!p) return '';
659
+ if (p.changed) return `<div class="insp-planned"><b>Planned:</b> ${esc(p.what || 'a change here')}<span>Does the diff below do this? truemap only knows that these files changed.</span></div>`;
660
+ return `<div class="insp-state">Planned, no changes in its files yet${p.what ? `: ${esc(p.what)}` : ''}</div>`;
661
+ }
662
+ // The inspector shows what changed in a box while you review changes.
663
+ function changeSection(box) {
664
+ const b = latestChanges?.boxes?.find((x) => x.src === box.src);
665
+ if (!b) return '';
666
+ ch.data = { base: { kind: latestChanges.base, label: latestChanges.label } };
667
+ return `<div class="insp-change"><div><span>Changed in the last turn</span>${delta(b.add, b.del)}</div>${b.files.map((p, i) => `<details${i === 0 ? ' open' : ''} data-path="${esc(p)}"><summary><span>${esc(p)}</span></summary><div class="code-box"></div></details>`).join('')}</div>`;
668
+ }
669
+ function wireChangeSection() {
670
+ for (const d of inspBody.querySelectorAll('.insp-change details')) {
671
+ const load = () => { if (d.open && !d.dataset.loaded) { d.dataset.loaded = '1'; loadDiff(d.dataset.path, d.querySelector('.code-box')); } };
672
+ d.addEventListener('toggle', load); load();
673
+ }
674
+ }
675
+
676
+
677
+ // ---------- plan review: the agent's plan on the map, approve or ask for changes ----------
678
+ // Requesting changes is a mode of the composer: a heading says so, Send sends the request (comments included).
679
+ function setRequest(on) {
680
+ planRequest = !!on;
681
+ const el = $('about');
682
+ if (on) {
683
+ el.hidden = false;
684
+ el.innerHTML = '<span><b>Requesting changes to the plan</b></span><button type="button" aria-label="Cancel">×</button>';
685
+ el.querySelector('button').onclick = () => setRequest(false);
686
+ input.placeholder = 'What should change? (comments above go along)';
687
+ input.focus(); scrollChat();
688
+ } else { renderAbout(); input.placeholder = state.notes.length ? S.placeholderNotes : S.placeholder; }
689
+ renderNotes();
690
+ }
691
+ const planBar = $('planbar');
692
+ let planRequest = false; // the next message asks for plan changes
693
+ function sendPlan() { state.planUnsupported = false; toFrame({ type: 'plan', plan: state.plan && state.plan.page === state.page ? state.plan : null }); }
694
+ function renderPlan() {
695
+ const p = state.plan;
696
+ if (!p || p.status === 'done' || state.planHidden === `${p.slug}:${p.status}`) { planBar.hidden = true; planBar.innerHTML = ''; return; }
697
+ planBar.hidden = false;
698
+ const counts = [p.add.length && `${p.add.length} new`, p.touch.length && `${p.touch.length} changing`, p.remove.length && `${p.remove.length} removed`].filter(Boolean).join(', ');
699
+ const here = p.page === state.page;
700
+ const old = here && state.planUnsupported;
701
+ // on its own map the plan's buttons sit beside its boxes; the bar is only a way there (or for old pages)
702
+ if (here && !old) { planBar.hidden = true; planBar.innerHTML = ''; renderNotes(); return; }
703
+ let html = `<div class="pb-text"><b>Plan</b><span class="pb-title">${esc(p.title)}</span><span class="pb-meta">${old ? 'not drawn: this page uses the old map format' : `${esc(counts)}${p.revision > 1 && p.status === 'review' ? ', revised' : ''}`}</span></div>`;
704
+ if (p.status === 'review' && old) {
705
+ html += `<div class="pb-acts"><span class="pb-wait">Read it in the conversation; the agent converts the map first.</span><button type="button" class="pb-btn" data-pb="request">Request changes</button><button type="button" class="pb-btn primary" data-pb="approve">Approve as text</button></div>`;
706
+ } else if (p.status === 'review') {
707
+ html += '<div class="pb-acts"><button type="button" class="pb-btn" data-pb="open" title="Review it where it is drawn">Show on the map</button></div>';
708
+ } else if (p.status === 'revise') {
709
+ html += `<div class="pb-acts"><span class="pb-wait">Waiting for the revised plan</span></div>`;
710
+ } else if (p.status === 'approved') {
711
+ const building = state.agent.state === 'working' && state.conn === 'live';
712
+ html += `<div class="pb-acts"><span class="pb-wait">${building ? `Approved. ${esc(agentName())} is building it.` : `Approved. Waiting for ${esc(agentName())} to pick it up.`}</span><button type="button" class="pb-btn" data-pb="changes">See what changed</button><button type="button" class="pb-x" data-pb="hide" aria-label="Hide">×</button></div>`;
713
+ }
714
+ planBar.innerHTML = html;
715
+ renderNotes(); // the request button carries the comment count
716
+ }
717
+ planBar.addEventListener('click', async (e) => {
718
+ const act = e.target.closest('[data-pb]')?.dataset.pb;
719
+ const p = state.plan; if (!act || !p) return;
720
+ if (act === 'open') go(p.page);
721
+ else if (act === 'hide') { state.planHidden = `${p.slug}:${p.status}`; renderPlan(); }
722
+ else if (act === 'changes') { setPanel(true); scrollChat(); }
723
+ else if (act === 'request') { setPanel(true); setTab('convo'); setRequest(true); }
724
+ else if (act === 'approve') {
725
+ // comments written before approving still go to the agent, first
726
+ if (state.notes.length || input.value.trim()) { const t = input.value; input.value = ''; autosize(); await send(t, { approving: true }); }
727
+ await api('/api/plan', { action: 'approve' });
728
+ }
729
+ });
730
+
731
+ // ---------- projects: every truemap project running on this machine ----------
732
+ const projMenu = $('projMenu');
733
+ let projList = [];
734
+ const PSTATE = { listening: 'Agent listening', working: 'Agent working', idle: 'Agent stopped listening', offline: 'No agent' };
735
+ const needsYou = (p) => !p.self && (p.unread || p.asking || p.plan?.status === 'review');
736
+ function renderProjects() {
737
+ const self = projList.find((p) => p.self);
738
+ if (self) { $('projName').textContent = self.name; try { window.name = `truemap-${self.name}`; } catch { /* ignore */ } }
739
+ const n = projList.filter(needsYou).length;
740
+ $('projCount').hidden = !n; $('projCount').textContent = n ? `${n} waiting` : '';
741
+ $('projBtn').title = n ? `${n} other project${n > 1 ? 's' : ''} need${n > 1 ? '' : 's'} you` : 'Projects';
742
+ const p = state.pages.find((x) => x.page === state.page);
743
+ document.title = `${n ? `(${n}) ` : ''}${p ? `${titleOf(p)} – ` : ''}${self ? self.name : 'truemap'}`;
744
+ if (projMenu.hidden) return;
745
+ projMenu.innerHTML = projList.map((x) => {
746
+ const why = x.plan?.status === 'review' ? `<em>Plan to review</em> ${esc(x.plan.title)}` : x.asking ? '<em>Waiting for your decision</em>' : x.unread ? '<em>New reply</em>' : esc(PSTATE[x.agent] || '');
747
+ return `<a class="proj-item${x.self ? ' self' : ''}" role="menuitem" ${x.self ? '' : `href="${esc(x.url)}" target="truemap-${esc(x.name)}"`} data-self="${x.self ? 1 : ''}"><i class="${esc(x.agent || '')}"></i><b>${esc(x.name)}</b><small>${why}</small></a>`;
748
+ }).join('') + `<div class="proj-foot">Projects with truemap running. Run <code>${esc(state.cmd)}</code> in another repo to add it.</div>`;
749
+ }
750
+ async function loadProjects() {
751
+ try { projList = (await fetch(`/api/projects?t=${encodeURIComponent(TOKEN)}`).then((r) => r.json())).projects || []; } catch { return; }
752
+ renderProjects();
753
+ }
754
+ $('projBtn').onclick = (e) => {
755
+ e.stopPropagation();
756
+ if (!projMenu.hidden) { projMenu.hidden = true; $('projBtn').setAttribute('aria-expanded', 'false'); return; }
757
+ projMenu.hidden = false; $('projBtn').setAttribute('aria-expanded', 'true'); renderProjects(); loadProjects();
758
+ };
759
+ projMenu.addEventListener('click', (e) => { const a = e.target.closest('.proj-item'); if (a?.dataset.self) e.preventDefault(); projMenu.hidden = true; $('projBtn').setAttribute('aria-expanded', 'false'); });
760
+ document.addEventListener('click', (e) => { if (!projMenu.hidden && !e.target.closest('.projects')) { projMenu.hidden = true; $('projBtn').setAttribute('aria-expanded', 'false'); } });
761
+ setInterval(() => { if (state.conn === 'live') loadProjects(); }, 15_000);
762
+
312
763
  // ---------- agent state ----------
313
764
  let tick = null;
314
765
  function renderWorking() {
@@ -322,7 +773,8 @@
322
773
  const s = state.conn === 'closed' ? 'closed' : state.agent.state;
323
774
  const shown = s === 'working' && isStale() ? 'stale' : s;
324
775
  $('agent').dataset.state = shown;
325
- $('agentLabel').textContent = S.state[shown] ? S.state[shown](agentName()) : shown;
776
+ $('agentLabel').textContent = S.state[shown] || shown;
777
+ $('agent').title = S.stateLong[shown] ? S.stateLong[shown](agentName()) : '';
326
778
  clearInterval(tick);
327
779
  const el = $('elapsed');
328
780
  if (s === 'working' && state.agent.since) {
@@ -333,7 +785,7 @@
333
785
  };
334
786
  upd(); el.hidden = false; tick = setInterval(upd, 1000);
335
787
  } else el.hidden = true;
336
- renderWorking(); renderNotice();
788
+ renderWorking(); renderNotice(); if (typeof renderPlan === "function" && state.plan) renderPlan();
337
789
  }
338
790
  function renderNotice() {
339
791
  const n = $('notice');
@@ -344,14 +796,14 @@
344
796
  let html = '';
345
797
  if (s === 'closed') {
346
798
  html = `<b>This workspace is closed</b>Your pages are still in <code>.truemap/</code>. To reopen this page, ask your agent to run:${cmdBox(state.cmd + page)}`;
347
- } else if (s === 'offline') {
348
- html = `<b>Your messages will wait here</b>To get answers, ask your agent in its terminal session to run:${listen}`;
349
- } else if (s === 'idle') {
350
- html = `<b>Your messages will wait here</b>To continue, ask ${esc(agentName())} in the terminal to run:${listen}`;
799
+ } else if ((s === 'offline' || s === 'idle') && (state.pending.size || !state.history.length)) {
800
+ html = `<b>${s === 'idle' ? `${esc(agentName())} stopped listening.` : 'No agent is listening.'}</b> ${state.pending.size ? 'Your message waits here;' : 'To talk from here,'} ask your agent to run${listen}`;
351
801
  } else if (s === 'working' && isStale()) {
352
802
  html = `<b>No reply for ${Math.round(STALE_MS / 60000)} minutes</b>${esc(agentName())} may have stopped, or be waiting for you in the terminal. Check there, or ask it to run:${listen}<p class="after">If it no longer knows your last comments, send them again.</p>`;
353
803
  }
804
+ const atEnd = msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight < 40;
354
805
  n.innerHTML = html; n.hidden = !html;
806
+ if (atEnd) scrollChat();
355
807
  n.querySelector('.copy')?.addEventListener('click', (e) => {
356
808
  const text = n.querySelector('.cmd code').textContent;
357
809
  navigator.clipboard?.writeText(text).then(() => { e.target.textContent = 'Copied'; setTimeout(() => { e.target.textContent = 'Copy'; }, 1400); }).catch(() => {});
@@ -373,11 +825,16 @@
373
825
  text = String(text || '').trim();
374
826
  const withNotes = !extra.answer && !extra.noNotes;
375
827
  const notes = withNotes ? state.notes : [];
376
- const context = extra.context ?? notes.map((n) => ({ kind: n.kind, label: n.label, src: n.src, excerpt: n.excerpt, comment: n.text, page: n.page }));
828
+ let context = extra.context ?? notes.map((n) => ({ kind: n.kind, label: n.label, src: n.src, excerpt: n.excerpt, comment: n.text, page: n.page }));
829
+ const about = !extra.context && !extra.answer && state.about;
830
+ if (about) context = [...context, { kind: 'element', label: about.label, src: about.src, excerpt: about.excerpt || '', page: state.page }];
377
831
  if (!text && !context.length && !extra.answer) return;
832
+ const reviewingPlan = state.plan?.status === 'review' && state.plan.page === state.page && state.notes.length && !extra.noNotes;
833
+ if ((planRequest || reviewingPlan) && !extra.answer && !extra.approving) { extra = { ...extra, plan: 'request' }; setRequest(false); }
378
834
  const r = await api('/api/send', { text, context, page: state.page, ...extra });
379
835
  if (r.id && !r.delivered) { state.pending.add(r.id); markPending(r.id, true); }
380
836
  if (withNotes && notes.length && r.id) { state.notes = []; renderNotes(); syncFrameNotes(); }
837
+ if (about && r.id) { state.about = null; renderAbout(); input.placeholder = S.placeholder; }
381
838
  }
382
839
 
383
840
  const autosize = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 180) + 'px'; };
@@ -388,7 +845,7 @@
388
845
  $('composer').addEventListener('submit', (e) => {
389
846
  e.preventDefault();
390
847
  const text = input.value;
391
- if (!text.trim() && !state.notes.length) { input.focus(); return; }
848
+ if (!text.trim() && !state.notes.length && !planRequest) { input.focus(); return; }
392
849
  input.value = ''; autosize();
393
850
  send(text);
394
851
  });
@@ -397,8 +854,12 @@
397
854
  $('checkChip').onclick = () => {
398
855
  const r = resultFor(state.page);
399
856
  if (!r || (!r.counts.changed && !r.counts.broken)) return;
400
- setPanel(true);
401
- send(S.fixPrompt(`.truemap/${state.page}`, r.counts.changed, r.counts.broken), { context: [], noNotes: true });
857
+ const stale = r.anchors.filter((a) => a.state !== 'ok');
858
+ const broken = stale.filter((a) => a.state === 'broken').length;
859
+ pointAt(stale.map((a) => a.src), broken ? 'These boxes no longer match the code.' : 'The code under these boxes changed after this page was written.', 'truemap');
860
+ setPanel(true); setTab('convo');
861
+ if (!input.value.trim()) { input.value = `The code under ${stale.map((a) => a.src.split('#')[1] || a.path).join(', ')} changed. Check whether the map still says the right thing about ${stale.length > 1 ? 'them' : 'it'}: fix what is wrong, confirm the rest.`; autosize(); }
862
+ input.focus();
402
863
  };
403
864
 
404
865
  // A decision only counts as the user's if the user actually moved focus into the page.
@@ -406,14 +867,23 @@
406
867
  const userIsInFrame = () => document.activeElement === frame && state.frameFocusAt > 0;
407
868
 
408
869
  // ---------- messages from the page frame ----------
409
- window.addEventListener('message', (e) => {
870
+ window.addEventListener('message', async (e) => {
410
871
  if (e.source !== frame.contentWindow || e.origin !== CONTENT || !e.data || !e.data.__truemap) return;
411
872
  const d = e.data;
412
- if (d.type === 'loaded') {
873
+ if (d.type === 'press' || d.type === 'deselect') {
874
+ closeInspector();
875
+ } else if (d.type === 'nav') {
876
+ navigate(d.dir);
877
+ } else if (d.type === 'peek') {
878
+ if (d.box) openInspector(d.box);
879
+ } else if (d.type === 'peek-if-open') {
880
+ if (d.box && panelEl.classList.contains('inspecting')) openInspector(d.box);
881
+ } else if (d.type === 'loaded') {
413
882
  if (d.page && d.page !== state.page) setCurrent(d.page);
414
- renderHeader(); sendMarks();
415
- if (!state.annotateTouched && typeof d.annotate === 'boolean') state.annotate = d.annotate;
416
- setAnnotate(state.annotate);
883
+ closeInspector();
884
+ if (state.pendingFocus) { const pf = state.pendingFocus; state.pendingFocus = null; setTimeout(() => toFrame({ type: 'focus', note: '', who: agentName(), ...pf }), 60); }
885
+ renderHeader(); sendMarks(); showChangeBadges(); sendPlan(); renderPlan();
886
+ if (state.pendingOpen) { const src = state.pendingOpen; state.pendingOpen = null; setTimeout(() => toFrame({ type: 'open-box', src }), 80); }
417
887
  syncFrameNotes();
418
888
  const y = state.scroll[d.page]; if (y) toFrame({ type: 'scroll', y });
419
889
  } else if (d.type === 'scroll') {
@@ -426,12 +896,26 @@
426
896
  renderNotes(); syncFrameNotes();
427
897
  if (d.send) send(input.value).then(() => { input.value = ''; autosize(); });
428
898
  else if (!panelOpen() && !narrow()) setPanel(true, false);
899
+ } else if (d.type === 'plan-unsupported') {
900
+ state.planUnsupported = true; renderPlan();
901
+ } else if (d.type === 'focus-state') {
902
+ const n = Number(d.count) || 0;
903
+ $('litPill').hidden = !n || !!d.transient;
904
+ $('litText').textContent = n === 1 ? '1 box lit' : `${n} boxes lit`;
905
+ } else if (d.type === 'focus-cleared') {
906
+ $('litPill').hidden = true;
907
+ } else if (d.type === 'plan-act') {
908
+ if (d.act === 'approve') {
909
+ if (state.notes.length || input.value.trim()) { const t = input.value; input.value = ''; autosize(); await send(t, { approving: true }); }
910
+ await api('/api/plan', { action: 'approve' });
911
+ } else if (d.act === 'reject') {
912
+ await api('/api/plan', { action: 'reject' });
913
+ }
914
+ } else if (d.type === 'changes-names') {
915
+ for (const it of d.items || []) if (it && it.src) ch.names.set(String(it.src), String(it.name || '').slice(0, 80));
916
+ if (showingChanges()) renderChanges();
429
917
  } else if (d.type === 'note-remove') {
430
918
  state.notes = state.notes.filter((x) => x.id !== d.id); renderNotes(); syncFrameNotes();
431
- } else if (d.type === 'toggle-annotate') {
432
- setAnnotate(!state.annotate, { touched: true });
433
- } else if (d.type === 'annotate-off') {
434
- setAnnotate(false, { touched: true });
435
919
  } else if (d.type === 'answer') {
436
920
  const fromUser = d.trusted === true && userIsInFrame();
437
921
  send('', {
@@ -444,12 +928,15 @@
444
928
  }
445
929
  });
446
930
 
931
+ $('litClear').onclick = () => { toFrame({ type: 'clear-focus' }); $('litPill').hidden = true; };
932
+
447
933
  // ---------- live events from the server ----------
448
934
  let closedTimer = null;
935
+ let loadedBuild = null;
449
936
  function setConn(c) {
450
937
  if (state.conn === c) return;
451
938
  state.conn = c; app.dataset.conn = c;
452
- $('annotate').disabled = c === 'closed';
939
+ if (c === 'closed') { projList = []; renderProjects(); }
453
940
  renderHeader();
454
941
  renderAgent();
455
942
  }
@@ -465,16 +952,21 @@
465
952
  let d; try { d = JSON.parse(ev.data); } catch { return; }
466
953
  if (d.type === 'hello') {
467
954
  greeted = true; clearTimeout(guard); clearTimeout(closedTimer); closedTimer = null;
955
+ if (d.build && loadedBuild && d.build !== loadedBuild) { es.close(); location.reload(); return; }
956
+ loadedBuild = d.build || loadedBuild;
468
957
  setConn('live');
469
958
  state.pages = d.pages || []; state.check = d.check || { results: [] }; state.history = d.history || [];
470
959
  state.pending = new Set(d.pending || []);
471
960
  if (d.cmd) state.cmd = d.cmd;
472
961
  state.root = String(d.root || '');
473
- if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; $('annotate').setAttribute('aria-checked', String(d.annotate)); }
474
962
  $('ver').textContent = `truemap ${d.version}`;
963
+ loadProjects();
475
964
  $('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
476
965
  state.agent = { state: d.agent?.state || 'offline', name: d.agent?.name || '', since: d.agent?.since || 0 };
477
- renderAll(); renderAgent(); renderNotes();
966
+ state.plan = d.plan || null;
967
+ renderAll(); renderAgent(); renderNotes(); renderPlan();
968
+ const last = [...state.history].reverse().find((h) => h.role === 'agent');
969
+ if (!panelOpen() && !narrow() && (state.plan?.status === 'review' || (last?.ask && !state.history.some((h) => h.kind === 'answer' && h.at > last.at)))) setPanel(true, false);
478
970
  const fromHash = decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || '');
479
971
  const target = [state.page, fromHash, d.current].find((p) => p && state.pages.some((x) => x.page === p)) || state.pages[0]?.page;
480
972
  target ? go(target, { force: !frame.getAttribute('src') }) : showEmpty();
@@ -498,15 +990,39 @@
498
990
  state.check = d.check || { results: [] }; renderHeader(); sendMarks(); if (!menu.hidden) renderMenu();
499
991
  } else if (d.type === 'navigate') {
500
992
  if (d.pages) state.pages = d.pages;
501
- if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; }
502
993
  if (d.page && state.pages.some((p) => p.page === d.page)) go(d.page, { force: true });
503
- else setAnnotate(state.annotate);
504
994
  renderHeader();
995
+ } else if (d.type === 'show') {
996
+ if (d.clear) toFrame({ type: 'clear-focus' });
997
+ else pointAt(d.focus || [], d.note || '', AGENTS[d.agent] || agentName(), d.page);
998
+ } else if (d.type === 'plan') {
999
+ if (hoverLit && hoverLit !== '__pinned') { hoverLit = null; msgsEl.querySelector('li.lit')?.classList.remove('lit'); toFrame({ type: 'clear-focus' }); }
1000
+ $('litPill').hidden = true; toFrame({ type: 'clear-focus' });
1001
+ state.plan = d.plan || null; renderPlan(); sendPlan(); renderNotes();
1002
+ } else if (d.type === 'changes-base') {
1003
+ } else if (d.type === 'view') {
1004
+ if (d.view === 'changes') { setPanel(true); scrollChat(); }
505
1005
  } else if (d.type === 'closing') {
506
- es.close(); setConn('closed');
1006
+ es.close();
1007
+ if (d.restart) setTimeout(connect, 700); else setConn('closed');
507
1008
  }
508
1009
  };
509
1010
  }
1011
+ function navigate(dir) {
1012
+ const from = dir === 'back' ? nav.back : nav.fwd; const to = dir === 'back' ? nav.fwd : nav.back;
1013
+ while (from.length) {
1014
+ const page = from.pop();
1015
+ if (state.pages.some((p) => p.page === page)) { if (state.page) to.push(state.page); nav.moving = true; go(page); return; }
1016
+ }
1017
+ }
1018
+ $('crumbHome').onclick = () => { if (state.page !== 'index.html') go('index.html'); };
1019
+ $('navBack').onclick = () => navigate('back');
1020
+ $('navFwd').onclick = () => navigate('forward');
1021
+ function renderNav() { $('navBack').disabled = !nav.back.length; $('navFwd').disabled = !nav.fwd.length; }
1022
+ document.addEventListener('keydown', (e) => {
1023
+ if (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) { e.preventDefault(); navigate(e.key === 'ArrowLeft' ? 'back' : 'forward'); }
1024
+ });
1025
+ window.addEventListener('mouseup', (e) => { if (e.button === 3) navigate('back'); else if (e.button === 4) navigate('forward'); });
510
1026
  renderNotes();
511
1027
  connect();
512
1028
  })();