truemap-cli 0.0.0-stage → 0.2.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.
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/bin/truemap.js +10 -0
- package/kit/fonts/OFL.txt +93 -0
- package/kit/fonts/ibm-plex-mono-latin-400-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-mono-latin-500-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-400-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-500-normal.woff2 +0 -0
- package/kit/fonts/ibm-plex-sans-latin-600-normal.woff2 +0 -0
- package/kit/truemap.css +290 -0
- package/package.json +39 -4
- package/skills/truemap/SKILL.md +23 -0
- package/src/check.js +248 -0
- package/src/cli.js +392 -0
- package/src/common.js +99 -0
- package/src/guide.md +143 -0
- package/src/outline.js +71 -0
- package/src/server.js +440 -0
- package/src/ui/sdk.js +470 -0
- package/src/ui/workspace.css +209 -0
- package/src/ui/workspace.html +76 -0
- package/src/ui/workspace.js +476 -0
|
@@ -0,0 +1,476 @@
|
|
|
1
|
+
(() => {
|
|
2
|
+
const TOKEN = window.TRUEMAP_TOKEN;
|
|
3
|
+
const CONTENT = window.TRUEMAP_CONTENT;
|
|
4
|
+
|
|
5
|
+
const AGENTS = { 'claude-code': 'Claude Code', codex: 'Codex' };
|
|
6
|
+
const S = {
|
|
7
|
+
placeholder: 'Ask about this page', placeholderNotes: 'Add a message (optional)',
|
|
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`,
|
|
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
|
+
chose: 'Chose', fromPage: 'Sent by the page’s own script', waiting: 'Waiting for the agent', you: 'You',
|
|
12
|
+
state: {
|
|
13
|
+
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
|
+
},
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
const $ = (id) => document.getElementById(id);
|
|
19
|
+
const app = $('app'); const frame = $('frame'); const msgsEl = $('msgs'); const input = $('input'); const menu = $('menu');
|
|
20
|
+
const state = {
|
|
21
|
+
pages: [], check: { results: [] }, page: null, history: [], pending: new Set(), scroll: {},
|
|
22
|
+
notes: [], agent: { state: 'offline', name: '', since: 0 }, progress: '', cmd: 'npx -y truemap-cli',
|
|
23
|
+
annotate: false, annotateTouched: false, conn: 'live', frameFocusAt: 0,
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
const store = {
|
|
27
|
+
get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
|
|
28
|
+
set: (k, v) => { try { localStorage.setItem(k, v); } catch { /* ignore */ } },
|
|
29
|
+
};
|
|
30
|
+
const api = (path, body) => fetch(path, {
|
|
31
|
+
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Truemap-Token': TOKEN }, body: JSON.stringify(body || {}),
|
|
32
|
+
}).then((r) => r.json()).catch(() => ({}));
|
|
33
|
+
const toFrame = (msg) => { if (state.page && !frame.hidden) frame.contentWindow?.postMessage({ __truemap: true, ...msg }, CONTENT); };
|
|
34
|
+
const agentName = () => AGENTS[state.agent.name] || 'The agent';
|
|
35
|
+
|
|
36
|
+
// ---------- text helpers ----------
|
|
37
|
+
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
38
|
+
const timeOf = (iso) => {
|
|
39
|
+
try {
|
|
40
|
+
const d = new Date(iso); const t = d.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
|
|
41
|
+
return d.toDateString() === new Date().toDateString() ? t : `${d.toLocaleDateString([], { month: 'short', day: 'numeric' })}, ${t}`;
|
|
42
|
+
} catch { return ''; }
|
|
43
|
+
};
|
|
44
|
+
function inline(s) {
|
|
45
|
+
return s
|
|
46
|
+
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
|
47
|
+
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
48
|
+
.replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?![*\w])/g, '$1<em>$2</em>')
|
|
49
|
+
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, href) => {
|
|
50
|
+
if (/^[\w./-]+\.html?(#[\w-]*)?$/i.test(href)) return `<a href="#" data-page="${href}">${t}</a>`;
|
|
51
|
+
if (/^https:\/\/[^\s"'<>]+$/i.test(href)) return `<a href="${href}" target="_blank" rel="noopener noreferrer">${t}</a>`;
|
|
52
|
+
return t;
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
function md(text) {
|
|
56
|
+
const lines = esc(text).split('\n');
|
|
57
|
+
let html = ''; let list = null; let code = null; let para = [];
|
|
58
|
+
const flush = () => { if (para.length) { html += `<p>${inline(para.join('<br>'))}</p>`; para = []; } };
|
|
59
|
+
const close = () => { if (list) { html += `</${list}>`; list = null; } };
|
|
60
|
+
for (const line of lines) {
|
|
61
|
+
if (code !== null) { if (/^```/.test(line)) { html += `<pre><code>${code}</code></pre>`; code = null; } else code += line + '\n'; continue; }
|
|
62
|
+
if (/^```/.test(line)) { flush(); close(); code = ''; continue; }
|
|
63
|
+
let m;
|
|
64
|
+
if ((m = line.match(/^\s*[-*]\s+(.*)/))) { flush(); if (list !== 'ul') { close(); html += '<ul>'; list = 'ul'; } html += `<li>${inline(m[1])}</li>`; continue; }
|
|
65
|
+
if ((m = line.match(/^\s*\d+[.)]\s+(.*)/))) { flush(); if (list !== 'ol') { close(); html += '<ol>'; list = 'ol'; } html += `<li>${inline(m[1])}</li>`; continue; }
|
|
66
|
+
if ((m = line.match(/^#{1,4}\s+(.*)/))) { flush(); close(); html += `<h4>${inline(m[1])}</h4>`; continue; }
|
|
67
|
+
if (!line.trim()) { flush(); close(); continue; }
|
|
68
|
+
close(); para.push(line);
|
|
69
|
+
}
|
|
70
|
+
if (code !== null) html += `<pre><code>${code}</code></pre>`;
|
|
71
|
+
flush(); close();
|
|
72
|
+
return html;
|
|
73
|
+
}
|
|
74
|
+
const fmtElapsed = (ms) => { const s = Math.max(0, Math.round(ms / 1000)); return s < 60 ? `${s}s` : `${Math.floor(s / 60)}m ${String(s % 60).padStart(2, '0')}s`; };
|
|
75
|
+
|
|
76
|
+
// ---------- conversation panel: one button opens and closes it ----------
|
|
77
|
+
const narrow = () => window.matchMedia('(max-width: 860px)').matches;
|
|
78
|
+
const panelOpen = () => !app.classList.contains('panel-closed');
|
|
79
|
+
function setPanel(open, remember = true) {
|
|
80
|
+
app.classList.toggle('panel-closed', !open);
|
|
81
|
+
const b = $('togglePanel');
|
|
82
|
+
b.setAttribute('aria-pressed', String(open));
|
|
83
|
+
b.title = open ? 'Hide conversation' : 'Show conversation';
|
|
84
|
+
b.setAttribute('aria-label', b.title);
|
|
85
|
+
if (open) state.unread = false;
|
|
86
|
+
renderBadge();
|
|
87
|
+
if (remember && !narrow()) store.set('truemap.panel', open ? 'open' : 'closed');
|
|
88
|
+
}
|
|
89
|
+
// While the panel is closed its button carries what is waiting there: pending comments, or a new answer.
|
|
90
|
+
function renderBadge() {
|
|
91
|
+
const u = $('unread'); const open = panelOpen(); const n = state.notes?.length || 0;
|
|
92
|
+
u.hidden = open || (!n && !state.unread);
|
|
93
|
+
u.textContent = !open && n ? String(n) : '';
|
|
94
|
+
u.classList.toggle('count', !open && n > 0);
|
|
95
|
+
}
|
|
96
|
+
setPanel(narrow() ? false : store.get('truemap.panel') !== 'closed', false);
|
|
97
|
+
$('togglePanel').onclick = () => { const open = !panelOpen(); setPanel(open); if (open) input.focus(); };
|
|
98
|
+
|
|
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
|
+
|
|
110
|
+
// ---------- page switcher ----------
|
|
111
|
+
const resultFor = (page) => state.check.results?.find((r) => r.page === page);
|
|
112
|
+
const stateOf = (r) => (r?.counts?.broken ? 'broken' : r?.counts?.changed ? 'changed' : '');
|
|
113
|
+
const titleOf = (p) => (p.page === 'index.html' && (!p.title || p.title === 'index') ? 'Blueprint' : p.title || p.page);
|
|
114
|
+
|
|
115
|
+
function renderMenu() {
|
|
116
|
+
const list = $('pages'); list.innerHTML = '';
|
|
117
|
+
const q = $('filter').value.trim().toLowerCase();
|
|
118
|
+
$('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>';
|
|
131
|
+
}
|
|
132
|
+
function openMenu() { renderMenu(); menu.hidden = false; $('pageBtn').setAttribute('aria-expanded', 'true'); ($('filter').hidden ? menu.querySelector('.page-item.active, .page-item') : $('filter'))?.focus(); }
|
|
133
|
+
function closeMenu() { menu.hidden = true; $('pageBtn').setAttribute('aria-expanded', 'false'); }
|
|
134
|
+
$('pageBtn').onclick = () => (menu.hidden ? openMenu() : closeMenu());
|
|
135
|
+
$('filter').addEventListener('input', renderMenu);
|
|
136
|
+
document.addEventListener('click', (e) => { if (!menu.hidden && !e.target.closest('.switcher')) closeMenu(); });
|
|
137
|
+
window.addEventListener('blur', () => { if (!menu.hidden) closeMenu(); });
|
|
138
|
+
document.addEventListener('keydown', (e) => {
|
|
139
|
+
const typing = e.target.closest?.('input,textarea,select,[contenteditable]');
|
|
140
|
+
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
|
|
141
|
+
else if (e.key === 'Escape' && !menu.hidden) { closeMenu(); $('pageBtn').focus(); }
|
|
142
|
+
else if (e.key === 'Escape' && !typing && state.annotate) setAnnotate(false, { touched: true });
|
|
143
|
+
else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
|
144
|
+
const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
|
|
145
|
+
e.preventDefault();
|
|
146
|
+
const i = items.indexOf(document.activeElement);
|
|
147
|
+
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
|
+
}
|
|
151
|
+
});
|
|
152
|
+
$('recheck').onclick = () => { api('/api/check'); closeMenu(); };
|
|
153
|
+
|
|
154
|
+
function renderHeader() {
|
|
155
|
+
const p = state.pages.find((x) => x.page === state.page);
|
|
156
|
+
$('pageTitle').textContent = p ? titleOf(p) : (state.pages.length ? 'Pages' : 'No pages yet');
|
|
157
|
+
$('pagePath').textContent = state.page ? `.truemap/${state.page}` : '';
|
|
158
|
+
document.title = p ? `${titleOf(p)} – truemap` : 'truemap';
|
|
159
|
+
const r = resultFor(state.page); const st = stateOf(r);
|
|
160
|
+
const chip = $('checkChip');
|
|
161
|
+
if (!r || r.missing || !r.anchors?.length || state.conn === 'closed') { chip.hidden = true; return; }
|
|
162
|
+
chip.hidden = false;
|
|
163
|
+
const { changed, broken } = r.counts;
|
|
164
|
+
chip.dataset.state = st || 'ok';
|
|
165
|
+
$('checkText').textContent = broken ? S.broken(broken) + (changed ? `, ${S.changed(changed)}` : '') : changed ? S.changed(changed) : S.ok;
|
|
166
|
+
chip.title = st ? 'Ask the agent to update this page' : `${r.counts.ok} boxes checked against the code`;
|
|
167
|
+
}
|
|
168
|
+
function sendMarks() {
|
|
169
|
+
const r = resultFor(state.page);
|
|
170
|
+
toFrame({ type: 'marks', items: (r?.anchors || []).filter((a) => a.state !== 'ok').map((a) => ({ src: a.src, state: a.state })) });
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
const pageUrl = (page, bust) => `${CONTENT}/pages/${page.split('/').map(encodeURIComponent).join('/')}${bust ? `?r=${Date.now()}` : ''}`;
|
|
174
|
+
function go(page, { force = false } = {}) {
|
|
175
|
+
if (!page) return showEmpty();
|
|
176
|
+
$('empty').hidden = true; frame.hidden = false;
|
|
177
|
+
if (state.page !== page || force) frame.src = pageUrl(page);
|
|
178
|
+
setCurrent(page);
|
|
179
|
+
}
|
|
180
|
+
function setCurrent(page) {
|
|
181
|
+
state.page = page;
|
|
182
|
+
history.replaceState(null, '', `${location.pathname}${location.search}#page=${encodeURIComponent(page)}`);
|
|
183
|
+
api('/api/viewing', { page });
|
|
184
|
+
renderHeader(); renderNotice(); renderNotes();
|
|
185
|
+
}
|
|
186
|
+
function showEmpty() {
|
|
187
|
+
state.page = null; frame.hidden = true; frame.removeAttribute('src'); $('empty').hidden = false; renderHeader(); renderNotice();
|
|
188
|
+
}
|
|
189
|
+
const reloadFrame = () => { if (state.page) frame.src = pageUrl(state.page, true); };
|
|
190
|
+
|
|
191
|
+
// ---------- notes (comments collected in annotate mode) ----------
|
|
192
|
+
const notesForPage = () => state.notes.filter((n) => n.page === state.page);
|
|
193
|
+
function syncFrameNotes() { toFrame({ type: 'notes', items: notesForPage().map(({ id, kind, label, src, text, selector, rect }) => ({ id, kind, label, src, text, selector, rect })) }); }
|
|
194
|
+
// Unsent comments survive a reload of this tab.
|
|
195
|
+
try { state.notes = JSON.parse(sessionStorage.getItem('truemap.notes') || '[]'); } catch { state.notes = []; }
|
|
196
|
+
function saveNotes() { try { sessionStorage.setItem('truemap.notes', JSON.stringify(state.notes)); } catch { /* ignore */ } }
|
|
197
|
+
function renderNotes() {
|
|
198
|
+
saveNotes(); renderBadge();
|
|
199
|
+
const list = $('notes'); list.innerHTML = '';
|
|
200
|
+
list.hidden = state.notes.length === 0;
|
|
201
|
+
state.notes.forEach((n, i) => {
|
|
202
|
+
const li = document.createElement('li'); li.className = 'note';
|
|
203
|
+
li.innerHTML = `<span class="mn-num">${i + 1}</span><span class="mn-what"><b>${esc(n.kind === 'text' ? `“${n.label}”` : n.label)}</b>${n.page !== state.page ? ` on ${esc(n.page)}` : ''}</span><span class="note-text">${esc(n.text)}</span><button class="note-x" type="button" aria-label="Remove comment" title="Remove">×</button>`;
|
|
204
|
+
li.querySelector('.note-x').onclick = (e) => { e.stopPropagation(); state.notes = state.notes.filter((x) => x.id !== n.id); renderNotes(); syncFrameNotes(); };
|
|
205
|
+
li.onclick = () => { if (n.page !== state.page) go(n.page); else toFrame({ type: 'focus-note', id: n.id }); };
|
|
206
|
+
list.appendChild(li);
|
|
207
|
+
});
|
|
208
|
+
const count = state.notes.length;
|
|
209
|
+
$('send').textContent = count ? `Send ${count} comment${count > 1 ? 's' : ''}` : 'Send';
|
|
210
|
+
input.placeholder = count ? S.placeholderNotes : S.placeholder;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// ---------- conversation ----------
|
|
214
|
+
function whoLine(role, at, name) {
|
|
215
|
+
const el = document.createElement('div'); el.className = 'who';
|
|
216
|
+
el.innerHTML = `<b>${esc(role === 'agent' ? (AGENTS[name] || name || agentName()) : S.you)}</b><span>${timeOf(at)}</span>`;
|
|
217
|
+
return el;
|
|
218
|
+
}
|
|
219
|
+
let lastRole = null;
|
|
220
|
+
function renderAll() {
|
|
221
|
+
msgsEl.innerHTML = ''; lastRole = null;
|
|
222
|
+
if (!state.history.length) {
|
|
223
|
+
msgsEl.innerHTML = `<div class="intro"><h2>Ask about anything on the page</h2><ol>
|
|
224
|
+
<li>Turn on <b>Annotate</b> (or press <kbd>A</kbd>), then click a box or select text to comment on it.</li>
|
|
225
|
+
<li>Add as many comments as you like. They go out together, each with the code it points to.</li>
|
|
226
|
+
<li>Or just type a question below.</li></ol></div>`;
|
|
227
|
+
}
|
|
228
|
+
for (const e of state.history) appendEntry(e, false);
|
|
229
|
+
renderWorking();
|
|
230
|
+
scrollChat();
|
|
231
|
+
}
|
|
232
|
+
function appendEntry(e, scroll = true, live = false) {
|
|
233
|
+
msgsEl.querySelector('.intro')?.remove();
|
|
234
|
+
if (e.role !== lastRole) { msgsEl.appendChild(whoLine(e.role, e.at, e.agent)); lastRole = e.role; }
|
|
235
|
+
const el = document.createElement('div');
|
|
236
|
+
if (e.role === 'agent') {
|
|
237
|
+
el.className = 'msg agent';
|
|
238
|
+
el.innerHTML = md(e.text);
|
|
239
|
+
if (live && !panelOpen()) { state.unread = true; renderBadge(); }
|
|
240
|
+
} else {
|
|
241
|
+
el.className = 'msg user'; el.dataset.id = e.id;
|
|
242
|
+
let body = '';
|
|
243
|
+
if (e.kind === 'answer') {
|
|
244
|
+
body = `<span class="answer-q">${esc(e.answer?.question || '')}</span>${esc(S.chose)}: <strong>${esc(e.answer?.choice || '')}</strong>${e.answer?.note ? `<br>${esc(e.answer.note)}` : ''}`;
|
|
245
|
+
} else {
|
|
246
|
+
const notes = (e.context || []).filter((c) => c.comment);
|
|
247
|
+
const sel = (e.context || []).filter((c) => !c.comment);
|
|
248
|
+
if (notes.length) {
|
|
249
|
+
body += `<ol class="msg-notes">${notes.map((c, i) => `<li class="mn"><span class="mn-num">${i + 1}</span><span class="mn-what"><b>${esc(c.kind === 'text' ? `“${c.label}”` : c.label)}</b>${c.src ? ` ${esc(c.src)}` : ''}</span><span>${esc(c.comment)}</span></li>`).join('')}</ol>`;
|
|
250
|
+
}
|
|
251
|
+
if (sel.length) body += `<div class="mn-what">${sel.map((c) => `<b>${esc(c.label)}</b>`).join(', ')}</div>`;
|
|
252
|
+
if (e.text) body += `<div class="msg-text">${esc(e.text).replace(/\n/g, '<br>')}</div>`;
|
|
253
|
+
}
|
|
254
|
+
el.innerHTML = body
|
|
255
|
+
+ (e.from === 'page' ? `<div class="from-page">${S.fromPage}</div>` : '')
|
|
256
|
+
+ (state.pending.has(e.id) ? `<div class="waiting">${S.waiting}</div>` : '');
|
|
257
|
+
}
|
|
258
|
+
msgsEl.appendChild(el);
|
|
259
|
+
renderWorking();
|
|
260
|
+
if (scroll) scrollChat();
|
|
261
|
+
}
|
|
262
|
+
const scrollChat = () => { msgsEl.scrollTop = msgsEl.scrollHeight; };
|
|
263
|
+
msgsEl.addEventListener('click', (e) => {
|
|
264
|
+
const a = e.target.closest('a[data-page]');
|
|
265
|
+
if (!a) return;
|
|
266
|
+
e.preventDefault();
|
|
267
|
+
const [page] = a.dataset.page.split('#');
|
|
268
|
+
if (state.pages.some((p) => p.page === page)) go(page);
|
|
269
|
+
});
|
|
270
|
+
function markPending(id, on) {
|
|
271
|
+
const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(id)}"]`);
|
|
272
|
+
if (!el) return;
|
|
273
|
+
el.querySelector('.waiting')?.remove();
|
|
274
|
+
if (on) el.insertAdjacentHTML('beforeend', `<div class="waiting">${S.waiting}</div>`);
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// ---------- agent state ----------
|
|
278
|
+
let tick = null;
|
|
279
|
+
function renderWorking() {
|
|
280
|
+
msgsEl.querySelector('.working')?.remove();
|
|
281
|
+
if (state.agent.state !== 'working' || state.conn !== 'live' || isStale()) return;
|
|
282
|
+
const w = document.createElement('div'); w.className = 'working';
|
|
283
|
+
w.innerHTML = `<i></i><span>${esc(state.progress || `${agentName()} is working on it`)}</span>`;
|
|
284
|
+
msgsEl.appendChild(w);
|
|
285
|
+
}
|
|
286
|
+
function renderAgent() {
|
|
287
|
+
const s = state.conn === 'closed' ? 'closed' : state.agent.state;
|
|
288
|
+
const shown = s === 'working' && isStale() ? 'stale' : s;
|
|
289
|
+
$('agent').dataset.state = shown;
|
|
290
|
+
$('agentLabel').textContent = S.state[shown] ? S.state[shown](agentName()) : shown;
|
|
291
|
+
clearInterval(tick);
|
|
292
|
+
const el = $('elapsed');
|
|
293
|
+
if (s === 'working' && state.agent.since) {
|
|
294
|
+
let stale = isStale();
|
|
295
|
+
const upd = () => {
|
|
296
|
+
el.textContent = fmtElapsed(Date.now() - state.agent.since);
|
|
297
|
+
if (isStale() !== stale) { stale = !stale; renderAgent(); }
|
|
298
|
+
};
|
|
299
|
+
upd(); el.hidden = false; tick = setInterval(upd, 1000);
|
|
300
|
+
} else el.hidden = true;
|
|
301
|
+
renderWorking(); renderNotice();
|
|
302
|
+
}
|
|
303
|
+
function renderNotice() {
|
|
304
|
+
const n = $('notice');
|
|
305
|
+
const s = state.conn === 'closed' ? 'closed' : state.agent.state;
|
|
306
|
+
const page = state.page && state.page !== 'index.html' ? ` ${state.page}` : '';
|
|
307
|
+
// One pattern for every state that needs the user: what is true, what to do, the command to give the agent.
|
|
308
|
+
const listen = cmdBox(`${state.cmd} listen`);
|
|
309
|
+
let html = '';
|
|
310
|
+
if (s === 'closed') {
|
|
311
|
+
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)}`;
|
|
312
|
+
} else if (s === 'offline') {
|
|
313
|
+
html = `<b>Your messages will wait here</b>To get answers, ask your agent in its terminal session to run:${listen}`;
|
|
314
|
+
} else if (s === 'idle') {
|
|
315
|
+
html = `<b>Your messages will wait here</b>To continue, ask ${esc(agentName())} in the terminal to run:${listen}`;
|
|
316
|
+
} else if (s === 'working' && isStale()) {
|
|
317
|
+
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>`;
|
|
318
|
+
}
|
|
319
|
+
n.innerHTML = html; n.hidden = !html;
|
|
320
|
+
n.querySelector('.copy')?.addEventListener('click', (e) => {
|
|
321
|
+
const text = n.querySelector('.cmd code').textContent;
|
|
322
|
+
navigator.clipboard?.writeText(text).then(() => { e.target.textContent = 'Copied'; setTimeout(() => { e.target.textContent = 'Copy'; }, 1400); }).catch(() => {});
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
const STALE_MS = 3 * 60 * 1000;
|
|
326
|
+
const isStale = () => state.agent.state === 'working' && state.conn === 'live'
|
|
327
|
+
&& Date.now() - Math.max(state.agent.since || 0, state.lastAgentEvent || 0) > STALE_MS;
|
|
328
|
+
const cmdBox = (cmd) => `<div class="cmd"><code>${esc(cmd)}</code><button class="copy" type="button">Copy</button></div>`;
|
|
329
|
+
function setAgent(a) {
|
|
330
|
+
if (!a) return;
|
|
331
|
+
state.agent = { state: a.state || 'offline', name: a.name || state.agent.name, since: a.since || 0 };
|
|
332
|
+
if (state.agent.state !== 'working') state.progress = '';
|
|
333
|
+
renderAgent();
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
// ---------- sending ----------
|
|
337
|
+
async function send(text, extra = {}) {
|
|
338
|
+
text = String(text || '').trim();
|
|
339
|
+
const withNotes = !extra.answer && !extra.noNotes;
|
|
340
|
+
const notes = withNotes ? state.notes : [];
|
|
341
|
+
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 }));
|
|
342
|
+
if (!text && !context.length && !extra.answer) return;
|
|
343
|
+
const r = await api('/api/send', { text, context, page: state.page, ...extra });
|
|
344
|
+
if (r.id && !r.delivered) { state.pending.add(r.id); markPending(r.id, true); }
|
|
345
|
+
if (withNotes && notes.length && r.id) { state.notes = []; renderNotes(); syncFrameNotes(); }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
const autosize = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 180) + 'px'; };
|
|
349
|
+
input.addEventListener('input', autosize);
|
|
350
|
+
input.addEventListener('keydown', (e) => {
|
|
351
|
+
if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && e.keyCode !== 229) { e.preventDefault(); $('composer').requestSubmit(); }
|
|
352
|
+
});
|
|
353
|
+
$('composer').addEventListener('submit', (e) => {
|
|
354
|
+
e.preventDefault();
|
|
355
|
+
const text = input.value;
|
|
356
|
+
if (!text.trim() && !state.notes.length) { input.focus(); return; }
|
|
357
|
+
input.value = ''; autosize();
|
|
358
|
+
send(text);
|
|
359
|
+
});
|
|
360
|
+
|
|
361
|
+
$('drawBlueprint').onclick = () => { setPanel(true); send(S.drawPrompt, { context: [], noNotes: true }); };
|
|
362
|
+
$('checkChip').onclick = () => {
|
|
363
|
+
const r = resultFor(state.page);
|
|
364
|
+
if (!r || (!r.counts.changed && !r.counts.broken)) return;
|
|
365
|
+
setPanel(true);
|
|
366
|
+
send(S.fixPrompt(`.truemap/${state.page}`, r.counts.changed, r.counts.broken), { context: [], noNotes: true });
|
|
367
|
+
};
|
|
368
|
+
|
|
369
|
+
// A decision only counts as the user's if the user actually moved focus into the page.
|
|
370
|
+
window.addEventListener('blur', () => { setTimeout(() => { if (document.activeElement === frame) state.frameFocusAt = Date.now(); }, 0); });
|
|
371
|
+
const userIsInFrame = () => document.activeElement === frame && state.frameFocusAt > 0;
|
|
372
|
+
|
|
373
|
+
// ---------- messages from the page frame ----------
|
|
374
|
+
window.addEventListener('message', (e) => {
|
|
375
|
+
if (e.source !== frame.contentWindow || e.origin !== CONTENT || !e.data || !e.data.__truemap) return;
|
|
376
|
+
const d = e.data;
|
|
377
|
+
if (d.type === 'loaded') {
|
|
378
|
+
if (d.page && d.page !== state.page) setCurrent(d.page);
|
|
379
|
+
renderHeader(); sendMarks();
|
|
380
|
+
if (!state.annotateTouched && typeof d.annotate === 'boolean') state.annotate = d.annotate;
|
|
381
|
+
setAnnotate(state.annotate);
|
|
382
|
+
syncFrameNotes();
|
|
383
|
+
const y = state.scroll[d.page]; if (y) toFrame({ type: 'scroll', y });
|
|
384
|
+
} else if (d.type === 'scroll') {
|
|
385
|
+
state.scroll[d.page] = d.y;
|
|
386
|
+
} else if (d.type === 'note' || d.type === 'note-update') {
|
|
387
|
+
const n = d.note || {};
|
|
388
|
+
const note = { id: String(n.id), page: d.page, kind: n.kind === 'text' ? 'text' : 'element', label: String(n.label || '').slice(0, 80), src: String(n.src || ''), excerpt: String(n.excerpt || '').slice(0, 400), text: String(n.text || '').slice(0, 4000), selector: String(n.selector || ''), rect: n.rect && typeof n.rect === 'object' ? { left: +n.rect.left || 0, top: +n.rect.top || 0, right: +n.rect.right || 0, bottom: +n.rect.bottom || 0 } : null };
|
|
389
|
+
const i = state.notes.findIndex((x) => x.id === note.id);
|
|
390
|
+
if (i >= 0) state.notes[i] = note; else state.notes.push(note);
|
|
391
|
+
renderNotes(); syncFrameNotes();
|
|
392
|
+
if (d.send) send(input.value).then(() => { input.value = ''; autosize(); });
|
|
393
|
+
else if (!panelOpen() && !narrow()) setPanel(true, false);
|
|
394
|
+
} else if (d.type === 'note-remove') {
|
|
395
|
+
state.notes = state.notes.filter((x) => x.id !== d.id); renderNotes(); syncFrameNotes();
|
|
396
|
+
} else if (d.type === 'toggle-annotate') {
|
|
397
|
+
setAnnotate(!state.annotate, { touched: true });
|
|
398
|
+
} else if (d.type === 'annotate-off') {
|
|
399
|
+
setAnnotate(false, { touched: true });
|
|
400
|
+
} else if (d.type === 'answer') {
|
|
401
|
+
const fromUser = d.trusted === true && userIsInFrame();
|
|
402
|
+
send('', {
|
|
403
|
+
kind: 'answer', from: fromUser ? 'user' : 'page', noNotes: true,
|
|
404
|
+
context: d.src ? [{ kind: 'element', label: d.question, src: d.src }] : [],
|
|
405
|
+
answer: { question: d.question, choice: d.choice, note: d.note },
|
|
406
|
+
});
|
|
407
|
+
} else if (d.type === 'page-send') {
|
|
408
|
+
if (d.text) send(d.text, { from: 'page', context: [], noNotes: true });
|
|
409
|
+
}
|
|
410
|
+
});
|
|
411
|
+
|
|
412
|
+
// ---------- live events from the server ----------
|
|
413
|
+
let closedTimer = null;
|
|
414
|
+
function setConn(c) {
|
|
415
|
+
if (state.conn === c) return;
|
|
416
|
+
state.conn = c; app.dataset.conn = c;
|
|
417
|
+
$('annotate').disabled = c === 'closed';
|
|
418
|
+
renderHeader();
|
|
419
|
+
renderAgent();
|
|
420
|
+
}
|
|
421
|
+
function connect() {
|
|
422
|
+
const es = new EventSource(`/api/events?t=${encodeURIComponent(TOKEN)}`);
|
|
423
|
+
let greeted = false;
|
|
424
|
+
const guard = setTimeout(() => { if (!greeted) { es.close(); connect(); } }, 3000);
|
|
425
|
+
es.onerror = () => {
|
|
426
|
+
if (closedTimer) return;
|
|
427
|
+
closedTimer = setTimeout(() => { if (es.readyState !== EventSource.OPEN) setConn('closed'); }, 5000);
|
|
428
|
+
};
|
|
429
|
+
es.onmessage = (ev) => {
|
|
430
|
+
let d; try { d = JSON.parse(ev.data); } catch { return; }
|
|
431
|
+
if (d.type === 'hello') {
|
|
432
|
+
greeted = true; clearTimeout(guard); clearTimeout(closedTimer); closedTimer = null;
|
|
433
|
+
setConn('live');
|
|
434
|
+
state.pages = d.pages || []; state.check = d.check || { results: [] }; state.history = d.history || [];
|
|
435
|
+
state.pending = new Set(d.pending || []);
|
|
436
|
+
if (d.cmd) state.cmd = d.cmd;
|
|
437
|
+
if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; $('annotate').setAttribute('aria-checked', String(d.annotate)); }
|
|
438
|
+
$('ver').textContent = `truemap ${d.version}`;
|
|
439
|
+
$('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
|
|
440
|
+
state.agent = { state: d.agent?.state || 'offline', name: d.agent?.name || '', since: d.agent?.since || 0 };
|
|
441
|
+
renderAll(); renderAgent(); renderNotes();
|
|
442
|
+
const fromHash = decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || '');
|
|
443
|
+
const target = [state.page, fromHash, d.current].find((p) => p && state.pages.some((x) => x.page === p)) || state.pages[0]?.page;
|
|
444
|
+
target ? go(target, { force: !frame.getAttribute('src') }) : showEmpty();
|
|
445
|
+
} else if (d.type === 'chat') {
|
|
446
|
+
state.history.push(d.entry); appendEntry(d.entry, true, true);
|
|
447
|
+
if (d.entry.role === 'agent') state.lastAgentEvent = Date.now();
|
|
448
|
+
} else if (d.type === 'agent') {
|
|
449
|
+
setAgent(d.agent);
|
|
450
|
+
} else if (d.type === 'delivered') {
|
|
451
|
+
for (const id of d.ids || []) { state.pending.delete(id); markPending(id, false); }
|
|
452
|
+
} else if (d.type === 'progress') {
|
|
453
|
+
state.progress = d.text || ''; state.lastAgentEvent = Date.now(); renderWorking(); renderNotice(); scrollChat();
|
|
454
|
+
} else if (d.type === 'pages') {
|
|
455
|
+
state.pages = d.pages || []; renderHeader(); if (!menu.hidden) renderMenu();
|
|
456
|
+
if (!state.page && state.pages[0]) go(state.pages[0].page);
|
|
457
|
+
else if (state.page && !state.pages.some((p) => p.page === state.page)) state.pages[0] ? go(state.pages[0].page) : showEmpty();
|
|
458
|
+
} else if (d.type === 'changed') {
|
|
459
|
+
const files = d.files || [];
|
|
460
|
+
if (state.page && files.some((f) => !f || f === state.page || f.startsWith('assets/'))) reloadFrame();
|
|
461
|
+
} else if (d.type === 'check') {
|
|
462
|
+
state.check = d.check || { results: [] }; renderHeader(); sendMarks(); if (!menu.hidden) renderMenu();
|
|
463
|
+
} else if (d.type === 'navigate') {
|
|
464
|
+
if (d.pages) state.pages = d.pages;
|
|
465
|
+
if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; }
|
|
466
|
+
if (d.page && state.pages.some((p) => p.page === d.page)) go(d.page, { force: true });
|
|
467
|
+
else setAnnotate(state.annotate);
|
|
468
|
+
renderHeader();
|
|
469
|
+
} else if (d.type === 'closing') {
|
|
470
|
+
es.close(); setConn('closed');
|
|
471
|
+
}
|
|
472
|
+
};
|
|
473
|
+
}
|
|
474
|
+
renderNotes();
|
|
475
|
+
connect();
|
|
476
|
+
})();
|