truemap-cli 0.3.0 → 0.5.0

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.
@@ -9,9 +9,10 @@
9
9
  ok: 'Matches the code', changed: (n) => `${n} changed in code`, broken: (n) => `${n} no longer match`,
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 = {
@@ -48,6 +49,7 @@
48
49
  .replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?![*\w])/g, '$1<em>$2</em>')
49
50
  .replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, href) => {
50
51
  if (/^[\w./-]+\.html?(#[\w-]*)?$/i.test(href)) return `<a href="#" data-page="${href}">${t}</a>`;
52
+ if (/^#[\w-]+$/.test(href)) return `<a href="#" class="ref" data-focus="${href.slice(1)}">${t}</a>`;
51
53
  if (/^https:\/\/[^\s"'<>]+$/i.test(href)) return `<a href="${href}" target="_blank" rel="noopener noreferrer">${t}</a>`;
52
54
  return t;
53
55
  });
@@ -96,16 +98,6 @@
96
98
  setPanel(narrow() ? false : store.get('truemap.panel') !== 'closed', false);
97
99
  $('togglePanel').onclick = () => { const open = !panelOpen(); setPanel(open); if (open) input.focus(); };
98
100
 
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
101
 
110
102
  // ---------- page switcher ----------
111
103
  const resultFor = (page) => state.check.results?.find((r) => r.page === page);
@@ -139,14 +131,11 @@
139
131
  const typing = e.target.closest?.('input,textarea,select,[contenteditable]');
140
132
  if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
141
133
  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
134
  else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
144
135
  const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
145
136
  e.preventDefault();
146
137
  const i = items.indexOf(document.activeElement);
147
138
  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
139
  }
151
140
  });
152
141
  $('recheck').onclick = () => { api('/api/check'); closeMenu(); };
@@ -189,19 +178,26 @@
189
178
  function renderHeader() {
190
179
  const p = state.pages.find((x) => x.page === state.page);
191
180
  $('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';
181
+ // The blueprint is always one click away.
182
+ const home = state.pages.find((x) => x.page === 'index.html');
183
+ const showHome = !!home && !!state.page && state.page !== 'index.html';
184
+ $('crumbHome').hidden = !showHome; $('crumbSep').hidden = !showHome;
185
+ if (showHome) { $('crumbHome').textContent = titleOf(home); $('crumbHome').title = `Back to ${titleOf(home)}`; }
186
+ renderProjects();
194
187
  const r = resultFor(state.page); const st = stateOf(r);
195
188
  const chip = $('checkChip');
196
189
  if (!r || r.missing || !r.anchors?.length || state.conn === 'closed') { chip.hidden = true; return; }
197
- chip.hidden = false;
190
+ chip.hidden = !st;
198
191
  const { changed, broken } = r.counts;
199
192
  chip.dataset.state = st || 'ok';
200
193
  $('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`;
194
+ chip.title = st ? 'Ask the agent to update this page' : `${S.ok}: ${r.counts.ok} boxes checked`;
195
+ if (!st) $('checkText').textContent = '';
196
+ chip.setAttribute('aria-label', st ? $('checkText').textContent : S.ok);
202
197
  }
203
198
  function sendMarks() {
204
199
  const r = resultFor(state.page);
200
+ if (panelEl.classList.contains('show-changes')) return toFrame({ type: 'marks', items: [] });
205
201
  toFrame({ type: 'marks', items: (r?.anchors || []).filter((a) => a.state !== 'ok').map((a) => ({ src: a.src, state: a.state })) });
206
202
  }
207
203
 
@@ -212,7 +208,11 @@
212
208
  if (state.page !== page || force) frame.src = pageUrl(page);
213
209
  setCurrent(page);
214
210
  }
211
+ // Back and forward between pages, like a browser (Alt+Left / Alt+Right, mouse side buttons).
212
+ const nav = { back: [], fwd: [], moving: false };
215
213
  function setCurrent(page) {
214
+ if (state.page && page !== state.page && !nav.moving) { nav.back.push(state.page); nav.fwd = []; if (nav.back.length > 50) nav.back.shift(); }
215
+ nav.moving = false;
216
216
  state.page = page;
217
217
  history.replaceState(null, '', `${location.pathname}${location.search}#page=${encodeURIComponent(page)}`);
218
218
  api('/api/viewing', { page });
@@ -223,12 +223,12 @@
223
223
  }
224
224
  const reloadFrame = () => { if (state.page) frame.src = pageUrl(state.page, true); };
225
225
 
226
- // ---------- notes (comments collected in annotate mode) ----------
226
+ // ---------- notes: comments on boxes or text, sent together ----------
227
227
  const notesForPage = () => state.notes.filter((n) => n.page === state.page);
228
228
  function syncFrameNotes() { toFrame({ type: 'notes', items: notesForPage().map(({ id, kind, label, src, text, selector, rect }) => ({ id, kind, label, src, text, selector, rect })) }); }
229
229
  // 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 */ } }
230
+ try { state.notes = JSON.parse(localStorage.getItem('truemap.notes') || '[]'); } catch { state.notes = []; }
231
+ function saveNotes() { try { localStorage.setItem('truemap.notes', JSON.stringify(state.notes)); } catch { /* ignore */ } }
232
232
  function renderNotes() {
233
233
  saveNotes(); renderBadge();
234
234
  const list = $('notes'); list.innerHTML = '';
@@ -241,13 +241,17 @@
241
241
  list.appendChild(li);
242
242
  });
243
243
  const count = state.notes.length;
244
- $('send').textContent = count ? `Send ${count} comment${count > 1 ? 's' : ''}` : 'Send';
245
- input.placeholder = count ? S.placeholderNotes : S.placeholder;
244
+ const reviewing = state.plan?.status === 'review' && state.plan.page === state.page;
245
+ $('send').textContent = planRequest ? 'Send request' : reviewing && count ? 'Send' : count ? `Send ${count} comment${count > 1 ? 's' : ''}` : 'Send';
246
+ const rq = planBar.querySelector('[data-pb="request"]');
247
+ 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)); }
248
+ $('send').classList.toggle('quiet', !!(reviewing && count));
249
+ if (!planRequest) input.placeholder = count ? S.placeholderNotes : S.placeholder;
246
250
  }
247
251
 
248
252
  // ---------- conversation ----------
249
253
  function whoLine(role, at, name) {
250
- const el = document.createElement('div'); el.className = 'who';
254
+ const el = document.createElement('div'); el.className = role === 'agent' ? 'who' : 'who you';
251
255
  el.innerHTML = `<b>${esc(role === 'agent' ? (AGENTS[name] || name || agentName()) : S.you)}</b><span>${timeOf(at)}</span>`;
252
256
  return el;
253
257
  }
@@ -255,14 +259,11 @@
255
259
  function renderAll() {
256
260
  msgsEl.innerHTML = ''; lastRole = null;
257
261
  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>`;
262
+ msgsEl.innerHTML = `<div class="intro"><p>Ask about anything on the page. <b>Click a box</b> to see what it is and comment on it; comments go out together, each with the code it points to.</p></div>`;
262
263
  }
263
264
  for (const e of state.history) appendEntry(e, false);
264
265
  renderWorking();
265
- scrollChat();
266
+ scrollChat(); requestAnimationFrame(scrollChat); setTimeout(scrollChat, 300);
266
267
  }
267
268
  function appendEntry(e, scroll = true, live = false) {
268
269
  msgsEl.querySelector('.intro')?.remove();
@@ -270,8 +271,15 @@
270
271
  const el = document.createElement('div');
271
272
  if (e.role === 'agent') {
272
273
  el.className = 'msg agent';
273
- el.innerHTML = md(e.text);
274
+ el.innerHTML = e.ask && e.text.trim() === e.ask.question.trim() ? '' : md(e.text);
275
+ for (const li of el.querySelectorAll('li')) if (li.querySelector('a.ref')) li.classList.add('has-ref');
276
+ if (e.focus?.length) {
277
+ if (!e.plan) el.insertAdjacentHTML('beforeend', `<p class="show-map"><a href="#" data-focus="${esc(e.focus.join(','))}">Show on the map</a></p>`);
278
+ if (live) pointAt(e.focus, '', AGENTS[e.agent] || agentName());
279
+ }
280
+ if (e.ask) el.appendChild(askCard(e));
274
281
  if (live && !panelOpen()) { state.unread = true; renderBadge(); }
282
+ if (live && panelEl.classList.contains('inspecting')) $('inspBack').classList.add('news');
275
283
  } else {
276
284
  el.className = 'msg user'; el.dataset.id = e.id;
277
285
  let body = '';
@@ -295,13 +303,168 @@
295
303
  if (scroll) scrollChat();
296
304
  }
297
305
  const scrollChat = () => { msgsEl.scrollTop = msgsEl.scrollHeight; };
306
+ let hoverLit = null;
307
+ msgsEl.addEventListener('mouseover', (e) => {
308
+ const host = e.target.closest('li.has-ref, a.ref');
309
+ const ids = host ? [...new Set([...(host.matches('a.ref') ? [host] : host.querySelectorAll('a.ref'))].flatMap((r) => r.dataset.focus.split(',')).filter(Boolean))] : null;
310
+ const key = ids ? ids.join(',') : null;
311
+ if (key === hoverLit || (!key && (hoverLit === '__pinned' || !hoverLit))) return;
312
+ msgsEl.querySelector('li.lit')?.classList.remove('lit');
313
+ hoverLit = key;
314
+ if (ids) { if (host.matches('li')) host.classList.add('lit'); toFrame({ type: 'focus', items: ids, note: '', who: '', scroll: false, transient: true }); }
315
+ else toFrame({ type: 'clear-focus' });
316
+ });
317
+ msgsEl.addEventListener('mouseleave', () => { if (hoverLit && hoverLit !== '__pinned') { hoverLit = null; msgsEl.querySelector('li.lit')?.classList.remove('lit'); toFrame({ type: 'clear-focus' }); } });
298
318
  msgsEl.addEventListener('click', (e) => {
319
+ const ref = e.target.closest('[data-focus]');
320
+ if (ref) { e.preventDefault(); hoverLit = '__pinned'; pointAt(ref.dataset.focus.split(',').filter(Boolean), '', ''); return; }
321
+ const step = e.target.closest('li.has-ref');
322
+ if (step) { hoverLit = '__pinned'; pointAt([...step.querySelectorAll('a.ref')].flatMap((r) => r.dataset.focus.split(',')).filter(Boolean), '', ''); return; }
323
+ const opt = e.target.closest('.ask-opt');
324
+ if (opt && !opt.disabled) { e.preventDefault(); answerAsk(opt); return; }
299
325
  const a = e.target.closest('a[data-page]');
300
326
  if (!a) return;
301
327
  e.preventDefault();
302
- const [page] = a.dataset.page.split('#');
303
- if (state.pages.some((p) => p.page === page)) go(page);
328
+ const [page, id] = a.dataset.page.split('#');
329
+ if (state.pages.some((p) => p.page === page)) { if (id) state.pendingFocus = { items: [id] }; go(page); }
304
330
  });
331
+
332
+ // ---------- the agent points at the map ----------
333
+ function pointAt(items, note, who, page) {
334
+ const target = page && state.pages.some((p) => p.page === page) ? page : state.page;
335
+ const msg = { type: 'focus', items, note: note || '', who: who || agentName() };
336
+ if (target && target !== state.page) { state.pendingFocus = msg; go(target); } else toFrame(msg);
337
+ }
338
+
339
+ // ---------- choices the agent asks for (only when it is blocked on a real trade-off) ----------
340
+ function askCard(e) {
341
+ const answered = state.history.find((h) => h.kind === 'answer' && h.answer?.question === e.ask.question && h.at > e.at)
342
+ || state.history.some((h) => h.role === 'agent' && h.ask && h.at > e.at); // a later question replaced this one
343
+ const box = document.createElement('div'); box.className = 'ask';
344
+ box.innerHTML = `<div class="ask-q">${esc(e.ask.question)}</div>` + e.ask.options.map((o, i) =>
345
+ `<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('');
346
+ box.dataset.q = e.ask.question;
347
+ return box;
348
+ }
349
+ function answerAsk(btn) {
350
+ const box = btn.closest('.ask');
351
+ for (const b of box.querySelectorAll('.ask-opt')) b.disabled = true;
352
+ btn.classList.add('chosen');
353
+ send('', { kind: 'answer', noNotes: true, context: [], answer: { question: box.dataset.q, choice: btn.querySelector('b').textContent, note: '' } });
354
+ }
355
+
356
+ // ---------- inspector: what a box is. It takes the panel's place until you go back. ----------
357
+ const panelEl = $('panel'); const inspBody = $('inspBody');
358
+ const pageHref = (href) => {
359
+ const [file, id] = href.split('#');
360
+ const base = state.page && state.page.includes('/') ? state.page.replace(/[^/]+$/, '') : '';
361
+ const parts = (base + file).split('/'); const outp = [];
362
+ for (const p of parts) { if (p === '..') outp.pop(); else if (p && p !== '.') outp.push(p); }
363
+ return { page: outp.join('/'), id };
364
+ };
365
+ const PLAN = { new: 'New in this plan', change: 'Changes in this plan', remove: 'Removed in this plan' };
366
+ let inspSeq = 0; let panelWasClosed = false;
367
+ const inspecting = () => panelEl.classList.contains('inspecting');
368
+ function closeInspector() {
369
+ if (!inspecting()) return;
370
+ panelEl.classList.remove('inspecting'); inspBody.innerHTML = ''; inspSeq++; app.classList.remove('wide-panel'); $('inspBack').classList.remove('news'); scrollChat();
371
+ toFrame({ type: 'select', id: null });
372
+ if (panelWasClosed) { panelWasClosed = false; setPanel(false, false); }
373
+ }
374
+ $('inspBack').onclick = () => closeInspector();
375
+ const absPath = (rel) => { const sep = String(state.root).includes('\\') ? '\\' : '/'; return [state.root, ...rel.split('/')].join(sep); };
376
+ async function loadCode(box, holder, seq) {
377
+ let sn = {};
378
+ 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' }; }
379
+ if (seq !== inspSeq) return; // another box was opened meanwhile
380
+ if (sn.kind === 'folder') holder.innerHTML = `<div class="code-note">A folder: ${esc(sn.path)}</div>`;
381
+ else if (sn.error) holder.innerHTML = `<div class="code-note">${esc(sn.error)}</div>`;
382
+ 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>`;
383
+ else {
384
+ 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>`;
385
+ const ed = inspBody.querySelector('.open-ed');
386
+ if (ed) { ed.href = `vscode://file/${absPath(sn.path).replace(/\\/g, '/')}:${sn.line}`; ed.hidden = false; }
387
+ const hit = holder.querySelector('.hit'); const pre = holder.querySelector('pre');
388
+ if (hit && pre) pre.scrollTop = Math.max(0, hit.offsetTop - pre.offsetTop - 44);
389
+ holder.closest('.insp-code')?.scrollIntoView({ block: 'nearest', behavior: 'smooth' });
390
+ }
391
+ }
392
+ function openInspector(box) {
393
+ const seq = ++inspSeq;
394
+ if (!panelOpen()) { panelWasClosed = true; setPanel(true, false); }
395
+ panelEl.classList.add('inspecting');
396
+ $('inspBack').lastChild.textContent = panelEl.classList.contains('show-changes') ? 'Changes' : 'Conversation';
397
+ toFrame({ type: 'select', id: box.id || null, src: box.src || '' });
398
+ 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('');
399
+ const page = box.href ? pageHref(box.href) : null;
400
+ const pageT = page && state.pages.find((p) => p.page === page.page);
401
+ let detail = ''; let list = false;
402
+ for (const d of box.detail || []) {
403
+ if (d.t === 'li' && !list) { detail += '<ul>'; list = true; }
404
+ if (d.t !== 'li' && list) { detail += '</ul>'; list = false; }
405
+ detail += d.t === 'li' ? `<li>${esc(d.text)}</li>` : `<p>${esc(d.text)}</p>`;
406
+ }
407
+ if (list) detail += '</ul>';
408
+ if (!detail && box.desc) detail = `<p>${esc(box.desc)}</p>`;
409
+ const rel = box.to.length || box.from.length;
410
+ inspBody.innerHTML = `
411
+ <div class="insp-name"><h2>${esc(box.label)}</h2>${box.tag ? `<code>${esc(box.tag)}</code>` : ''}</div>
412
+ ${PLAN[box.plan] ? `<span class="insp-plan">${PLAN[box.plan]}</span>${box.planNote ? `<p class="insp-why">${esc(box.planNote)}</p>` : ''}` : ''}
413
+ ${box.mark ? `<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>` : ''}
414
+ ${box.mark === 'changed' && 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>' : ''}
415
+ ${unbuiltNote(box)}${changeSection(box)}
416
+ ${detail ? `<div class="insp-detail">${detail}</div>` : ''}
417
+ ${box.why ? `<div class="insp-why">${esc(box.why)}</div>` : ''}
418
+ <form class="insp-comment"><textarea rows="1" aria-label="Comment"></textarea><button type="submit" disabled>Add</button></form>
419
+ ${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>` : ''}
420
+ ${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>`
421
+ : box.ext ? '<div class="insp-why">Outside this code base.</div>' : ''}
422
+ ${pageT ? `<div class="insp-actions">${pageT ? `<button type="button" data-act="open">Open ${esc(titleOf(pageT))}</button>` : ''}</div>` : ''}`;
423
+ inspBody.scrollTop = 0;
424
+ wireChangeSection();
425
+ const drift = inspBody.querySelector('.insp-drift .code-box');
426
+ if (drift) {
427
+ const a = resultFor(state.page)?.anchors?.find((x) => x.src === box.src);
428
+ fetch(`/api/drift?path=${encodeURIComponent(box.src.split('#')[0].replace(/\/+$/, ''))}&since=${encodeURIComponent(a?.since || '')}&t=${encodeURIComponent(TOKEN)}`).then((r) => r.json())
429
+ .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>'; })
430
+ .catch(() => { drift.innerHTML = '<div class="code-note">Could not read the diff.</div>'; });
431
+ }
432
+ const form = inspBody.querySelector('.insp-comment'); const ta = form.querySelector('textarea'); const add = form.querySelector('button');
433
+ ta.placeholder = `Comment on ${box.label}, or ask about it`;
434
+ ta.addEventListener('input', () => { add.disabled = !ta.value.trim(); ta.style.height = 'auto'; ta.style.height = Math.min(ta.scrollHeight, 140) + 'px'; });
435
+ ta.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); form.requestSubmit(); } });
436
+ form.onsubmit = (e) => {
437
+ e.preventDefault();
438
+ const text = ta.value.trim(); if (!text) return;
439
+ 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 });
440
+ renderNotes(); syncFrameNotes();
441
+ panelWasClosed = false; closeInspector(); input.focus();
442
+ };
443
+ const code = inspBody.querySelector('.insp-code');
444
+ if (code) code.addEventListener('toggle', () => { if (code.open && !code.dataset.loaded) { code.dataset.loaded = '1'; loadCode(box, code.querySelector('.code-box'), seq); } });
445
+ inspBody.querySelector('.open-ed')?.addEventListener('click', (e) => e.stopPropagation());
446
+ inspBody.onclick = (ev) => {
447
+ const chip = ev.target.closest('[data-box]');
448
+ if (chip) { toFrame({ type: 'open-box', id: chip.dataset.box }); return; }
449
+ const act = ev.target.closest('[data-act]')?.dataset.act;
450
+ if (act === 'open') { closeInspector(); if (page.id) state.pendingFocus = { type: 'focus', items: [page.id] }; go(page.page); }
451
+ else if (act === 'links') pointAt([box.id, ...box.to.map((c) => c.id), ...box.from.map((c) => c.id)], '', '');
452
+ };
453
+ }
454
+ document.addEventListener('keydown', (e) => {
455
+ if (e.key !== 'Escape' || !inspecting() || !menu.hidden || !$('moreMenu').hidden) return;
456
+ if (e.target.closest?.('.insp-comment') && e.target.value) return;
457
+ closeInspector(); toFrame({ type: 'clear-focus' }); e.stopPropagation();
458
+ }, true);
459
+
460
+ // "Ask about this": the box goes along with the next message.
461
+ function renderAbout() {
462
+ const el = $('about'); const a = state.about;
463
+ el.hidden = !a; if (!a) { el.innerHTML = ''; return; }
464
+ el.innerHTML = `<span>About <b>${esc(a.label)}</b>${a.src ? ` <code>${esc(a.src)}</code>` : ''}</span><button type="button" aria-label="Remove">×</button>`;
465
+ el.querySelector('button').onclick = () => { state.about = null; renderAbout(); };
466
+ input.placeholder = `Ask about ${a.label}`;
467
+ }
305
468
  function markPending(id, on) {
306
469
  const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(id)}"]`);
307
470
  if (!el) return;
@@ -309,6 +472,239 @@
309
472
  if (on) el.insertAdjacentHTML('beforeend', `<div class="waiting">${S.waiting}</div>`);
310
473
  }
311
474
 
475
+ // ---------- changes: what changed since a base, by box ----------
476
+ const tabs = { convo: $('tabConvo'), changes: $('tabChanges') };
477
+ const BASES = { turn: 'Since the agent’s last turn began', plan: 'Since you approved the plan', head: 'Uncommitted changes', main: 'This branch vs main' };
478
+ const ch = { base: store.get('truemap.base') || 'auto', data: null, names: new Map() };
479
+ const showingChanges = () => panelEl.classList.contains('show-changes');
480
+ function setTab(which) {
481
+ panelEl.classList.toggle('show-changes', which === 'changes');
482
+ tabs.convo.setAttribute('aria-selected', String(which !== 'changes'));
483
+ tabs.changes.setAttribute('aria-selected', String(which === 'changes'));
484
+ closeInspector();
485
+ if (which === 'changes') { renderChanges(); loadChanges(); }
486
+ sendChangeMarks(); sendMarks();
487
+ }
488
+ tabs.convo.onclick = () => setTab('convo');
489
+ tabs.changes.onclick = () => setTab('changes');
490
+ let loadingChanges = false;
491
+ async function loadChanges() {
492
+ if (state.conn !== 'live' || loadingChanges) return;
493
+ loadingChanges = true;
494
+ let r = null;
495
+ try { r = await fetch(`/api/changes?base=${encodeURIComponent(ch.base)}&t=${encodeURIComponent(TOKEN)}`).then((x) => x.json()); } catch { r = null; }
496
+ loadingChanges = false;
497
+ if (!r) return;
498
+ ch.data = r;
499
+ const n = r.error ? 0 : r.files;
500
+ $('changesCount').hidden = !n; $('changesCount').textContent = n ? String(n) : '';
501
+ if (showingChanges()) renderChanges();
502
+ sendChangeMarks();
503
+ }
504
+ function sendChangeMarks() {
505
+ const on = showingChanges() && ch.data && !ch.data.error;
506
+ toFrame({
507
+ 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 })) : [],
508
+ unbuilt: on && ch.data.plan ? ch.data.plan.planned.filter((p) => !p.changed).map((p) => ({ box: p.box, src: p.src, what: p.what })) : [],
509
+ });
510
+ }
511
+ 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>`;
512
+ const plural = (n, w) => `${n} ${w}${n === 1 ? '' : 's'}`;
513
+ function renderChanges() {
514
+ const el = $('changes'); const r = ch.data;
515
+ if (!r) { el.innerHTML = '<p class="ch-empty">Reading the working tree…</p>'; return; }
516
+ if (r.error) { el.innerHTML = `<p class="ch-empty">Changes need a git repository with at least one commit (${esc(r.error)}).</p>`; return; }
517
+ 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('');
518
+ 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>`;
519
+ if (r.plan) {
520
+ const done = r.plan.planned.filter((p) => p.changed).length; const missing = r.plan.planned.filter((p) => !p.changed);
521
+ 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>`;
522
+ const STEP = { done: 'Agent: done', partly: 'Agent: partly done', not_built: 'Agent: not built', dropped: 'Agent: dropped' };
523
+ const conflicts = (r.plan.steps || []).filter((st) => st.conflict || st.rewritten);
524
+ 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>`;
525
+ if (r.plan.steps?.length) {
526
+ html += `<ol class="ch-steps">${r.plan.steps.map((st) => {
527
+ const quiet = [...st.files.filter((x) => !x.changed).map((x) => x.path), ...st.boxes.filter((x) => !x.changed).map((x) => x.name)];
528
+ 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>`;
529
+ 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>`;
530
+ }).join('')}</ol>`;
531
+ }
532
+ 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>`;
533
+ html += '</div>';
534
+ }
535
+ const planned = new Set((r.plan?.planned || []).map((p) => p.src).filter(Boolean));
536
+ if (r.boxes.length) {
537
+ html += '<div class="ch-h">On the map</div>';
538
+ for (const b of r.boxes) {
539
+ const here = b.pages.includes(state.page);
540
+ const name = ch.names.get(b.src) || b.src.split('#')[1] || b.src.split('/').pop();
541
+ const other = here ? '' : `, on ${titleOf(state.pages.find((p) => p.page === b.pages[0]) || { page: b.pages[0] })}`;
542
+ const offPlan = r.plan && !planned.has(b.src) ? '<span class="off-plan">not in the plan</span>' : '';
543
+ const want = r.plan?.planned.find((p) => p.src === b.src)?.what;
544
+ 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>`;
545
+ }
546
+ }
547
+ if (r.unmapped.length) {
548
+ const n = r.unmapped.reduce((k, g) => k + g.files.length, 0);
549
+ html += `<div class="ch-h">Not on the map: ${plural(n, 'file')}</div>`;
550
+ for (const g of r.unmapped) {
551
+ const nameOfSrc = (src) => ch.names.get(src) || src.split('#')[1] || src.split('/').pop();
552
+ 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>`;
553
+ }
554
+ html += '<div class="ch-act"><button type="button" data-act="map">Ask the agent to map these</button></div>';
555
+ }
556
+ 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>';
557
+ el.innerHTML = html;
558
+ }
559
+ function diffHtml(text) {
560
+ const rows = []; let oldN = 0; let newN = 0;
561
+ for (const l of String(text || '').split('\n')) {
562
+ if (/^(diff --git|index |--- |\+\+\+ |new file|deleted file|similarity|rename |\\ No newline)/.test(l)) continue;
563
+ const h = l.match(/^@@ -(\d+)(?:,\d+)? \+(\d+)/);
564
+ if (h) { oldN = +h[1]; newN = +h[2]; rows.push(`<span class="hunk"><i></i>${esc(l.replace(/^@@[^@]*@@\s?/, '') || '…')}</span>`); continue; }
565
+ if (!l && !rows.length) continue;
566
+ const cls = l[0] === '+' ? 'add' : l[0] === '-' ? 'del' : '';
567
+ const n = cls === 'del' ? oldN++ : newN++; if (cls === '') oldN++;
568
+ rows.push(`<span class="${cls}"><i>${n}</i><em>${cls === 'add' ? '+' : cls === 'del' ? '−' : ' '}</em>${esc(l.slice(1)) || ' '}</span>`);
569
+ }
570
+ return rows.length ? `<pre>${rows.join('')}</pre>` : '<div class="code-note">No text changes (binary or mode only).</div>';
571
+ }
572
+ async function loadDiff(path, holder) {
573
+ holder.innerHTML = '<div class="code-note">Reading the diff…</div>';
574
+ let r = {};
575
+ 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' }; }
576
+ holder.innerHTML = r.error ? `<div class="code-note">${esc(r.error)}</div>` : diffHtml(r.text);
577
+ }
578
+ $('changes').addEventListener('change', (e) => {
579
+ if (e.target.id !== 'chBase') return;
580
+ ch.base = e.target.value; ch.userBase = true; store.set('truemap.base', ch.base); ch.data = null; renderChanges(); loadChanges();
581
+ });
582
+ $('changes').addEventListener('click', (e) => {
583
+ const row = e.target.closest('.ch-row');
584
+ if (row) {
585
+ if (row.dataset.page !== state.page) { state.pendingOpen = row.dataset.src; go(row.dataset.page); } else toFrame({ type: 'open-box', src: row.dataset.src });
586
+ return;
587
+ }
588
+ const file = e.target.closest('.ch-file');
589
+ if (file) {
590
+ const next = file.nextElementSibling;
591
+ if (next?.classList.contains('ch-diff')) { next.remove(); return; }
592
+ const box = document.createElement('div'); box.className = 'ch-diff code-box'; file.after(box); loadDiff(file.dataset.path, box);
593
+ return;
594
+ }
595
+ if (e.target.closest('[data-act="head"]')) { ch.base = 'head'; store.set('truemap.base', 'head'); ch.data = null; renderChanges(); loadChanges(); return; }
596
+ if (e.target.closest('[data-act="map"]')) {
597
+ const files = ch.data.unmapped.flatMap((g) => g.files.map((f) => f.path));
598
+ setTab('convo');
599
+ 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 });
600
+ }
601
+ });
602
+ function unbuiltNote(box) {
603
+ if (!showingChanges() || !ch.data?.plan) return '';
604
+ const p = ch.data.plan.planned.find((x) => (x.src && x.src === box.src) || x.box === box.id);
605
+ if (!p) return '';
606
+ 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>`;
607
+ return `<div class="insp-state">Planned, no changes in its files yet${p.what ? `: ${esc(p.what)}` : ''}</div>`;
608
+ }
609
+ // The inspector shows what changed in a box while you review changes.
610
+ function changeSection(box) {
611
+ if (!showingChanges() || !ch.data?.boxes) return '';
612
+ const b = ch.data.boxes.find((x) => x.src === box.src);
613
+ if (!b) return '';
614
+ return `<div class="insp-change"><div><span>${esc(ch.data.base.label)}</span>${b.files.length > 1 ? delta(b.add, b.del) : ''}</div>${b.files.map((f, i) => `<details${i === 0 ? ' open' : ''} data-path="${esc(f.path)}"><summary><span>${esc(f.path)}${f.shared ? `<span class="shared">shared with ${plural(f.shared, 'other box')}</span>` : ''}</span>${delta(f.add, f.del)}</summary><div class="code-box"></div></details>`).join('')}</div>`;
615
+ }
616
+ function wireChangeSection() {
617
+ for (const d of inspBody.querySelectorAll('.insp-change details')) {
618
+ const load = () => { if (d.open && !d.dataset.loaded) { d.dataset.loaded = '1'; loadDiff(d.dataset.path, d.querySelector('.code-box')); } };
619
+ d.addEventListener('toggle', load); load();
620
+ }
621
+ }
622
+ setInterval(() => { if (document.visibilityState === 'visible') loadChanges(); }, 10_000);
623
+
624
+ // ---------- plan review: the agent's plan on the map, approve or ask for changes ----------
625
+ // Requesting changes is a mode of the composer: a heading says so, Send sends the request (comments included).
626
+ function setRequest(on) {
627
+ planRequest = !!on;
628
+ const el = $('about');
629
+ if (on) {
630
+ el.hidden = false;
631
+ el.innerHTML = '<span><b>Requesting changes to the plan</b></span><button type="button" aria-label="Cancel">×</button>';
632
+ el.querySelector('button').onclick = () => setRequest(false);
633
+ input.placeholder = 'What should change? (comments above go along)';
634
+ input.focus(); scrollChat();
635
+ } else { renderAbout(); input.placeholder = state.notes.length ? S.placeholderNotes : S.placeholder; }
636
+ renderNotes();
637
+ }
638
+ const planBar = $('planbar');
639
+ let planRequest = false; // the next message asks for plan changes
640
+ function sendPlan() { state.planUnsupported = false; toFrame({ type: 'plan', plan: state.plan && state.plan.page === state.page ? state.plan : null }); }
641
+ function renderPlan() {
642
+ const p = state.plan;
643
+ if (!p || p.status === 'done' || state.planHidden === `${p.slug}:${p.status}`) { planBar.hidden = true; planBar.innerHTML = ''; return; }
644
+ planBar.hidden = false;
645
+ 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(', ');
646
+ const here = p.page === state.page;
647
+ const old = here && state.planUnsupported;
648
+ 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>`;
649
+ if (p.status === 'review' && old) {
650
+ 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>`;
651
+ } else if (p.status === 'review') {
652
+ html += `<div class="pb-acts">${here ? '' : '<button type="button" class="pb-btn" data-pb="open">Show on the map</button>'}<button type="button" class="pb-btn" data-pb="request">Request changes</button><button type="button" class="pb-btn primary" data-pb="approve">Approve</button></div>`;
653
+ } else if (p.status === 'revise') {
654
+ html += `<div class="pb-acts"><span class="pb-wait">Waiting for the revised plan</span></div>`;
655
+ } else if (p.status === 'approved') {
656
+ const building = state.agent.state === 'working' && state.conn === 'live';
657
+ 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>`;
658
+ }
659
+ planBar.innerHTML = html;
660
+ renderNotes(); // the request button carries the comment count
661
+ }
662
+ planBar.addEventListener('click', async (e) => {
663
+ const act = e.target.closest('[data-pb]')?.dataset.pb;
664
+ const p = state.plan; if (!act || !p) return;
665
+ if (act === 'open') go(p.page);
666
+ else if (act === 'hide') { state.planHidden = `${p.slug}:${p.status}`; renderPlan(); }
667
+ else if (act === 'changes') { ch.base = 'plan'; ch.data = null; setPanel(true); setTab('changes'); }
668
+ else if (act === 'request') { setPanel(true); setTab('convo'); setRequest(true); }
669
+ else if (act === 'approve') {
670
+ // comments written before approving still go to the agent, first
671
+ if (state.notes.length || input.value.trim()) { const t = input.value; input.value = ''; autosize(); await send(t, { approving: true }); }
672
+ await api('/api/plan', { action: 'approve' });
673
+ }
674
+ });
675
+
676
+ // ---------- projects: every truemap project running on this machine ----------
677
+ const projMenu = $('projMenu');
678
+ let projList = [];
679
+ const PSTATE = { listening: 'Agent listening', working: 'Agent working', idle: 'Agent stopped listening', offline: 'No agent' };
680
+ const needsYou = (p) => !p.self && (p.unread || p.asking || p.plan?.status === 'review');
681
+ function renderProjects() {
682
+ const self = projList.find((p) => p.self);
683
+ if (self) { $('projName').textContent = self.name; try { window.name = `truemap-${self.name}`; } catch { /* ignore */ } }
684
+ const n = projList.filter(needsYou).length;
685
+ $('projCount').hidden = !n; $('projCount').textContent = n ? `${n} waiting` : '';
686
+ $('projBtn').title = n ? `${n} other project${n > 1 ? 's' : ''} need${n > 1 ? '' : 's'} you` : 'Projects';
687
+ const p = state.pages.find((x) => x.page === state.page);
688
+ document.title = `${n ? `(${n}) ` : ''}${p ? `${titleOf(p)} – ` : ''}${self ? self.name : 'truemap'}`;
689
+ if (projMenu.hidden) return;
690
+ projMenu.innerHTML = projList.map((x) => {
691
+ 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] || '');
692
+ 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>`;
693
+ }).join('') + `<div class="proj-foot">Projects with truemap running. Run <code>${esc(state.cmd)}</code> in another repo to add it.</div>`;
694
+ }
695
+ async function loadProjects() {
696
+ try { projList = (await fetch(`/api/projects?t=${encodeURIComponent(TOKEN)}`).then((r) => r.json())).projects || []; } catch { return; }
697
+ renderProjects();
698
+ }
699
+ $('projBtn').onclick = (e) => {
700
+ e.stopPropagation();
701
+ if (!projMenu.hidden) { projMenu.hidden = true; $('projBtn').setAttribute('aria-expanded', 'false'); return; }
702
+ projMenu.hidden = false; $('projBtn').setAttribute('aria-expanded', 'true'); renderProjects(); loadProjects();
703
+ };
704
+ 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'); });
705
+ document.addEventListener('click', (e) => { if (!projMenu.hidden && !e.target.closest('.projects')) { projMenu.hidden = true; $('projBtn').setAttribute('aria-expanded', 'false'); } });
706
+ setInterval(() => { if (state.conn === 'live') loadProjects(); }, 15_000);
707
+
312
708
  // ---------- agent state ----------
313
709
  let tick = null;
314
710
  function renderWorking() {
@@ -322,7 +718,8 @@
322
718
  const s = state.conn === 'closed' ? 'closed' : state.agent.state;
323
719
  const shown = s === 'working' && isStale() ? 'stale' : s;
324
720
  $('agent').dataset.state = shown;
325
- $('agentLabel').textContent = S.state[shown] ? S.state[shown](agentName()) : shown;
721
+ $('agentLabel').textContent = S.state[shown] || shown;
722
+ $('agent').title = S.stateLong[shown] ? S.stateLong[shown](agentName()) : '';
326
723
  clearInterval(tick);
327
724
  const el = $('elapsed');
328
725
  if (s === 'working' && state.agent.since) {
@@ -333,7 +730,7 @@
333
730
  };
334
731
  upd(); el.hidden = false; tick = setInterval(upd, 1000);
335
732
  } else el.hidden = true;
336
- renderWorking(); renderNotice();
733
+ renderWorking(); renderNotice(); if (typeof renderPlan === "function" && state.plan) renderPlan();
337
734
  }
338
735
  function renderNotice() {
339
736
  const n = $('notice');
@@ -344,14 +741,14 @@
344
741
  let html = '';
345
742
  if (s === 'closed') {
346
743
  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}`;
744
+ } else if ((s === 'offline' || s === 'idle') && (state.pending.size || !state.history.length)) {
745
+ 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
746
  } else if (s === 'working' && isStale()) {
352
747
  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
748
  }
749
+ const atEnd = msgsEl.scrollHeight - msgsEl.scrollTop - msgsEl.clientHeight < 40;
354
750
  n.innerHTML = html; n.hidden = !html;
751
+ if (atEnd) scrollChat();
355
752
  n.querySelector('.copy')?.addEventListener('click', (e) => {
356
753
  const text = n.querySelector('.cmd code').textContent;
357
754
  navigator.clipboard?.writeText(text).then(() => { e.target.textContent = 'Copied'; setTimeout(() => { e.target.textContent = 'Copy'; }, 1400); }).catch(() => {});
@@ -373,11 +770,16 @@
373
770
  text = String(text || '').trim();
374
771
  const withNotes = !extra.answer && !extra.noNotes;
375
772
  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 }));
773
+ 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 }));
774
+ const about = !extra.context && !extra.answer && state.about;
775
+ if (about) context = [...context, { kind: 'element', label: about.label, src: about.src, excerpt: about.excerpt || '', page: state.page }];
377
776
  if (!text && !context.length && !extra.answer) return;
777
+ const reviewingPlan = state.plan?.status === 'review' && state.plan.page === state.page && state.notes.length && !extra.noNotes;
778
+ if ((planRequest || reviewingPlan) && !extra.answer && !extra.approving) { extra = { ...extra, plan: 'request' }; setRequest(false); }
378
779
  const r = await api('/api/send', { text, context, page: state.page, ...extra });
379
780
  if (r.id && !r.delivered) { state.pending.add(r.id); markPending(r.id, true); }
380
781
  if (withNotes && notes.length && r.id) { state.notes = []; renderNotes(); syncFrameNotes(); }
782
+ if (about && r.id) { state.about = null; renderAbout(); input.placeholder = S.placeholder; }
381
783
  }
382
784
 
383
785
  const autosize = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 180) + 'px'; };
@@ -388,7 +790,7 @@
388
790
  $('composer').addEventListener('submit', (e) => {
389
791
  e.preventDefault();
390
792
  const text = input.value;
391
- if (!text.trim() && !state.notes.length) { input.focus(); return; }
793
+ if (!text.trim() && !state.notes.length && !planRequest) { input.focus(); return; }
392
794
  input.value = ''; autosize();
393
795
  send(text);
394
796
  });
@@ -397,8 +799,12 @@
397
799
  $('checkChip').onclick = () => {
398
800
  const r = resultFor(state.page);
399
801
  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 });
802
+ const stale = r.anchors.filter((a) => a.state !== 'ok');
803
+ const broken = stale.filter((a) => a.state === 'broken').length;
804
+ 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');
805
+ setPanel(true); setTab('convo');
806
+ if (!input.value.trim()) { input.value = `Update this page: ${stale.map((a) => a.src.split('#')[1] || a.path).join(', ')} ${broken ? 'no longer match the code' : 'changed in the code'}.`; autosize(); }
807
+ input.focus();
402
808
  };
403
809
 
404
810
  // A decision only counts as the user's if the user actually moved focus into the page.
@@ -409,11 +815,18 @@
409
815
  window.addEventListener('message', (e) => {
410
816
  if (e.source !== frame.contentWindow || e.origin !== CONTENT || !e.data || !e.data.__truemap) return;
411
817
  const d = e.data;
412
- if (d.type === 'loaded') {
818
+ if (d.type === 'press' || d.type === 'deselect') {
819
+ closeInspector();
820
+ } else if (d.type === 'nav') {
821
+ navigate(d.dir);
822
+ } else if (d.type === 'peek') {
823
+ if (d.box) openInspector(d.box);
824
+ } else if (d.type === 'loaded') {
413
825
  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);
826
+ closeInspector();
827
+ if (state.pendingFocus) { const pf = state.pendingFocus; state.pendingFocus = null; setTimeout(() => toFrame({ type: 'focus', note: '', who: agentName(), ...pf }), 60); }
828
+ renderHeader(); sendMarks(); sendChangeMarks(); sendPlan(); renderPlan();
829
+ if (state.pendingOpen) { const src = state.pendingOpen; state.pendingOpen = null; setTimeout(() => toFrame({ type: 'open-box', src }), 80); }
417
830
  syncFrameNotes();
418
831
  const y = state.scroll[d.page]; if (y) toFrame({ type: 'scroll', y });
419
832
  } else if (d.type === 'scroll') {
@@ -426,12 +839,19 @@
426
839
  renderNotes(); syncFrameNotes();
427
840
  if (d.send) send(input.value).then(() => { input.value = ''; autosize(); });
428
841
  else if (!panelOpen() && !narrow()) setPanel(true, false);
842
+ } else if (d.type === 'plan-unsupported') {
843
+ state.planUnsupported = true; renderPlan();
844
+ } else if (d.type === 'focus-state') {
845
+ const n = Number(d.count) || 0;
846
+ $('litPill').hidden = !n || !!d.transient;
847
+ $('litText').textContent = n === 1 ? '1 box lit' : `${n} boxes lit`;
848
+ } else if (d.type === 'focus-cleared') {
849
+ $('litPill').hidden = true;
850
+ } else if (d.type === 'changes-names') {
851
+ for (const it of d.items || []) if (it && it.src) ch.names.set(String(it.src), String(it.name || '').slice(0, 80));
852
+ if (showingChanges()) renderChanges();
429
853
  } else if (d.type === 'note-remove') {
430
854
  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
855
  } else if (d.type === 'answer') {
436
856
  const fromUser = d.trusted === true && userIsInFrame();
437
857
  send('', {
@@ -444,12 +864,14 @@
444
864
  }
445
865
  });
446
866
 
867
+ $('litClear').onclick = () => { toFrame({ type: 'clear-focus' }); $('litPill').hidden = true; };
868
+
447
869
  // ---------- live events from the server ----------
448
870
  let closedTimer = null;
449
871
  function setConn(c) {
450
872
  if (state.conn === c) return;
451
873
  state.conn = c; app.dataset.conn = c;
452
- $('annotate').disabled = c === 'closed';
874
+ if (c === 'closed') { projList = []; renderProjects(); }
453
875
  renderHeader();
454
876
  renderAgent();
455
877
  }
@@ -470,11 +892,14 @@
470
892
  state.pending = new Set(d.pending || []);
471
893
  if (d.cmd) state.cmd = d.cmd;
472
894
  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
895
  $('ver').textContent = `truemap ${d.version}`;
896
+ loadProjects();
475
897
  $('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
476
898
  state.agent = { state: d.agent?.state || 'offline', name: d.agent?.name || '', since: d.agent?.since || 0 };
477
- renderAll(); renderAgent(); renderNotes();
899
+ state.plan = d.plan || null;
900
+ renderAll(); renderAgent(); renderNotes(); loadChanges(); renderPlan();
901
+ const last = [...state.history].reverse().find((h) => h.role === 'agent');
902
+ if (!panelOpen() && !narrow() && (state.plan?.status === 'review' || (last?.ask && !state.history.some((h) => h.kind === 'answer' && h.at > last.at)))) setPanel(true, false);
478
903
  const fromHash = decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || '');
479
904
  const target = [state.page, fromHash, d.current].find((p) => p && state.pages.some((x) => x.page === p)) || state.pages[0]?.page;
480
905
  target ? go(target, { force: !frame.getAttribute('src') }) : showEmpty();
@@ -498,15 +923,36 @@
498
923
  state.check = d.check || { results: [] }; renderHeader(); sendMarks(); if (!menu.hidden) renderMenu();
499
924
  } else if (d.type === 'navigate') {
500
925
  if (d.pages) state.pages = d.pages;
501
- if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; }
502
926
  if (d.page && state.pages.some((p) => p.page === d.page)) go(d.page, { force: true });
503
- else setAnnotate(state.annotate);
504
927
  renderHeader();
928
+ } else if (d.type === 'show') {
929
+ if (d.clear) toFrame({ type: 'clear-focus' });
930
+ else pointAt(d.focus || [], d.note || '', AGENTS[d.agent] || agentName(), d.page);
931
+ } else if (d.type === 'plan') {
932
+ if (hoverLit && hoverLit !== '__pinned') { hoverLit = null; msgsEl.querySelector('li.lit')?.classList.remove('lit'); toFrame({ type: 'clear-focus' }); }
933
+ $('litPill').hidden = true; toFrame({ type: 'clear-focus' });
934
+ state.plan = d.plan || null; renderPlan(); sendPlan(); renderNotes();
935
+ } else if (d.type === 'changes-base') {
936
+ loadChanges();
937
+ } else if (d.type === 'view') {
938
+ if (d.view === 'changes') { if (d.base && d.base !== 'auto' && !ch.userBase) { ch.base = d.base; ch.data = null; } setPanel(true); setTab('changes'); }
505
939
  } else if (d.type === 'closing') {
506
940
  es.close(); setConn('closed');
507
941
  }
508
942
  };
509
943
  }
944
+ function navigate(dir) {
945
+ const from = dir === 'back' ? nav.back : nav.fwd; const to = dir === 'back' ? nav.fwd : nav.back;
946
+ while (from.length) {
947
+ const page = from.pop();
948
+ if (state.pages.some((p) => p.page === page)) { if (state.page) to.push(state.page); nav.moving = true; go(page); return; }
949
+ }
950
+ }
951
+ $('crumbHome').onclick = () => go('index.html');
952
+ document.addEventListener('keydown', (e) => {
953
+ if (e.altKey && (e.key === 'ArrowLeft' || e.key === 'ArrowRight')) { e.preventDefault(); navigate(e.key === 'ArrowLeft' ? 'back' : 'forward'); }
954
+ });
955
+ window.addEventListener('mouseup', (e) => { if (e.button === 3) navigate('back'); else if (e.button === 4) navigate('forward'); });
510
956
  renderNotes();
511
957
  connect();
512
958
  })();