truemap-cli 0.1.0 → 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/README.md +29 -26
- package/bin/truemap.js +3 -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 +246 -186
- package/package.json +1 -1
- package/skills/truemap/SKILL.md +4 -3
- package/src/cli.js +46 -15
- package/src/guide.md +53 -31
- package/src/outline.js +71 -0
- package/src/server.js +440 -394
- package/src/ui/sdk.js +387 -58
- package/src/ui/workspace.css +179 -128
- package/src/ui/workspace.html +49 -46
- package/src/ui/workspace.js +241 -104
package/src/ui/workspace.js
CHANGED
|
@@ -2,27 +2,26 @@
|
|
|
2
2
|
const TOKEN = window.TRUEMAP_TOKEN;
|
|
3
3
|
const CONTENT = window.TRUEMAP_CONTENT;
|
|
4
4
|
|
|
5
|
+
const AGENTS = { 'claude-code': 'Claude Code', codex: 'Codex' };
|
|
5
6
|
const S = {
|
|
6
|
-
|
|
7
|
-
placeholder: 'Ask about this project, or select something on the page', placeholderCtx: 'Ask about the selection',
|
|
8
|
-
intro: 'Select a box or some text on the page, then ask about it. The agent receives the code it points to.',
|
|
7
|
+
placeholder: 'Ask about this page', placeholderNotes: 'Add a message (optional)',
|
|
9
8
|
drawPrompt: 'Read this project and draw its blueprint as .truemap/index.html, then open it for me.',
|
|
10
|
-
|
|
11
|
-
['Explain', 'Explain how this works.'],
|
|
12
|
-
['What uses it', 'What depends on this, and what does it depend on?'],
|
|
13
|
-
['Why like this', 'Why is it built this way? What are the trade-offs?'],
|
|
14
|
-
['Change it…', null],
|
|
15
|
-
],
|
|
16
|
-
changePrefix: 'Change it so that ',
|
|
17
|
-
ok: 'Matches the code', changed: (n) => `${n} changed in code`, broken: (n) => `${n} out of date`,
|
|
9
|
+
ok: 'Matches the code', changed: (n) => `${n} changed in code`, broken: (n) => `${n} no longer match`,
|
|
18
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(', ')}.`,
|
|
19
|
-
|
|
20
|
-
|
|
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
|
+
},
|
|
21
16
|
};
|
|
22
17
|
|
|
23
18
|
const $ = (id) => document.getElementById(id);
|
|
24
19
|
const app = $('app'); const frame = $('frame'); const msgsEl = $('msgs'); const input = $('input'); const menu = $('menu');
|
|
25
|
-
const state = {
|
|
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
|
+
};
|
|
26
25
|
|
|
27
26
|
const store = {
|
|
28
27
|
get: (k) => { try { return localStorage.getItem(k); } catch { return null; } },
|
|
@@ -32,14 +31,21 @@
|
|
|
32
31
|
method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Truemap-Token': TOKEN }, body: JSON.stringify(body || {}),
|
|
33
32
|
}).then((r) => r.json()).catch(() => ({}));
|
|
34
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
35
|
|
|
36
36
|
// ---------- text helpers ----------
|
|
37
37
|
const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
|
|
38
|
-
const timeOf = (iso) => {
|
|
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
|
+
};
|
|
39
44
|
function inline(s) {
|
|
40
45
|
return s
|
|
41
46
|
.replace(/`([^`]+)`/g, '<code>$1</code>')
|
|
42
47
|
.replace(/\*\*([^*]+)\*\*/g, '<strong>$1</strong>')
|
|
48
|
+
.replace(/(^|[^*\w])\*([^*\s][^*]*?)\*(?![*\w])/g, '$1<em>$2</em>')
|
|
43
49
|
.replace(/\[([^\]]+)\]\(([^)\s]+)\)/g, (_, t, href) => {
|
|
44
50
|
if (/^[\w./-]+\.html?(#[\w-]*)?$/i.test(href)) return `<a href="#" data-page="${href}">${t}</a>`;
|
|
45
51
|
if (/^https:\/\/[^\s"'<>]+$/i.test(href)) return `<a href="${href}" target="_blank" rel="noopener noreferrer">${t}</a>`;
|
|
@@ -65,24 +71,46 @@
|
|
|
65
71
|
flush(); close();
|
|
66
72
|
return html;
|
|
67
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`; };
|
|
68
75
|
|
|
69
|
-
// ----------
|
|
76
|
+
// ---------- conversation panel: one button opens and closes it ----------
|
|
70
77
|
const narrow = () => window.matchMedia('(max-width: 860px)').matches;
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
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 });
|
|
76
105
|
}
|
|
77
|
-
|
|
78
|
-
$('
|
|
79
|
-
$('
|
|
80
|
-
const chatOpen = () => !app.classList.contains('chat-closed');
|
|
106
|
+
state.annotate = store.get('truemap.annotate') === 'on';
|
|
107
|
+
$('annotate').setAttribute('aria-checked', String(state.annotate));
|
|
108
|
+
$('annotate').onclick = () => setAnnotate(!state.annotate, { touched: true });
|
|
81
109
|
|
|
82
110
|
// ---------- page switcher ----------
|
|
83
111
|
const resultFor = (page) => state.check.results?.find((r) => r.page === page);
|
|
84
112
|
const stateOf = (r) => (r?.counts?.broken ? 'broken' : r?.counts?.changed ? 'changed' : '');
|
|
85
|
-
const titleOf = (p) => (p.page === 'index.html' && (!p.title || p.title === 'index') ?
|
|
113
|
+
const titleOf = (p) => (p.page === 'index.html' && (!p.title || p.title === 'index') ? 'Blueprint' : p.title || p.page);
|
|
86
114
|
|
|
87
115
|
function renderMenu() {
|
|
88
116
|
const list = $('pages'); list.innerHTML = '';
|
|
@@ -94,11 +122,12 @@
|
|
|
94
122
|
const st = stateOf(resultFor(p.page));
|
|
95
123
|
const b = document.createElement('button');
|
|
96
124
|
b.type = 'button'; b.className = 'page-item' + (p.page === state.page ? ' active' : ''); b.setAttribute('role', 'menuitem');
|
|
97
|
-
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="
|
|
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>` : ''}`;
|
|
98
126
|
b.onclick = () => { closeMenu(); go(p.page); };
|
|
99
127
|
list.appendChild(b);
|
|
100
128
|
if (i === 0 && p.page === 'index.html' && arr.length > 1) list.insertAdjacentHTML('beforeend', '<div class="menu-gap"></div>');
|
|
101
129
|
});
|
|
130
|
+
if (!state.pages.length) list.innerHTML = '<div class="menu-head">No pages in .truemap/ yet</div>';
|
|
102
131
|
}
|
|
103
132
|
function openMenu() { renderMenu(); menu.hidden = false; $('pageBtn').setAttribute('aria-expanded', 'true'); ($('filter').hidden ? menu.querySelector('.page-item.active, .page-item') : $('filter'))?.focus(); }
|
|
104
133
|
function closeMenu() { menu.hidden = true; $('pageBtn').setAttribute('aria-expanded', 'false'); }
|
|
@@ -107,31 +136,34 @@
|
|
|
107
136
|
document.addEventListener('click', (e) => { if (!menu.hidden && !e.target.closest('.switcher')) closeMenu(); });
|
|
108
137
|
window.addEventListener('blur', () => { if (!menu.hidden) closeMenu(); });
|
|
109
138
|
document.addEventListener('keydown', (e) => {
|
|
139
|
+
const typing = e.target.closest?.('input,textarea,select,[contenteditable]');
|
|
110
140
|
if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === 'k') { e.preventDefault(); menu.hidden ? openMenu() : closeMenu(); }
|
|
111
141
|
else if (e.key === 'Escape' && !menu.hidden) { closeMenu(); $('pageBtn').focus(); }
|
|
142
|
+
else if (e.key === 'Escape' && !typing && state.annotate) setAnnotate(false, { touched: true });
|
|
112
143
|
else if (!menu.hidden && (e.key === 'ArrowDown' || e.key === 'ArrowUp')) {
|
|
113
144
|
const items = [...menu.querySelectorAll('.page-item')]; if (!items.length) return;
|
|
114
145
|
e.preventDefault();
|
|
115
146
|
const i = items.indexOf(document.activeElement);
|
|
116
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 });
|
|
117
150
|
}
|
|
118
151
|
});
|
|
119
152
|
$('recheck').onclick = () => { api('/api/check'); closeMenu(); };
|
|
120
153
|
|
|
121
154
|
function renderHeader() {
|
|
122
155
|
const p = state.pages.find((x) => x.page === state.page);
|
|
123
|
-
$('pageTitle').textContent = p ? titleOf(p) : '
|
|
156
|
+
$('pageTitle').textContent = p ? titleOf(p) : (state.pages.length ? 'Pages' : 'No pages yet');
|
|
124
157
|
$('pagePath').textContent = state.page ? `.truemap/${state.page}` : '';
|
|
125
158
|
document.title = p ? `${titleOf(p)} – truemap` : 'truemap';
|
|
126
159
|
const r = resultFor(state.page); const st = stateOf(r);
|
|
127
|
-
const dot = $('titleDot'); dot.hidden = !st; dot.className = `state-dot ${st}`;
|
|
128
160
|
const chip = $('checkChip');
|
|
129
|
-
if (!r || r.missing || !r.anchors?.length) { chip.hidden = true; return; }
|
|
161
|
+
if (!r || r.missing || !r.anchors?.length || state.conn === 'closed') { chip.hidden = true; return; }
|
|
130
162
|
chip.hidden = false;
|
|
131
163
|
const { changed, broken } = r.counts;
|
|
132
164
|
chip.dataset.state = st || 'ok';
|
|
133
|
-
|
|
134
|
-
chip.title = st ? 'Ask the agent to update this page' :
|
|
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`;
|
|
135
167
|
}
|
|
136
168
|
function sendMarks() {
|
|
137
169
|
const r = resultFor(state.page);
|
|
@@ -146,42 +178,85 @@
|
|
|
146
178
|
setCurrent(page);
|
|
147
179
|
}
|
|
148
180
|
function setCurrent(page) {
|
|
149
|
-
if (state.page !== page) { state.chips = []; renderChips(); }
|
|
150
181
|
state.page = page;
|
|
151
182
|
history.replaceState(null, '', `${location.pathname}${location.search}#page=${encodeURIComponent(page)}`);
|
|
152
183
|
api('/api/viewing', { page });
|
|
153
|
-
renderHeader();
|
|
184
|
+
renderHeader(); renderNotice(); renderNotes();
|
|
154
185
|
}
|
|
155
186
|
function showEmpty() {
|
|
156
|
-
state.page = null; frame.hidden = true; frame.removeAttribute('src'); $('empty').hidden = false; renderHeader();
|
|
187
|
+
state.page = null; frame.hidden = true; frame.removeAttribute('src'); $('empty').hidden = false; renderHeader(); renderNotice();
|
|
157
188
|
}
|
|
158
189
|
const reloadFrame = () => { if (state.page) frame.src = pageUrl(state.page, true); };
|
|
159
190
|
|
|
160
|
-
// ----------
|
|
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;
|
|
161
220
|
function renderAll() {
|
|
162
|
-
msgsEl.innerHTML =
|
|
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
|
+
}
|
|
163
228
|
for (const e of state.history) appendEntry(e, false);
|
|
229
|
+
renderWorking();
|
|
164
230
|
scrollChat();
|
|
165
231
|
}
|
|
166
|
-
function appendEntry(e, scroll = true) {
|
|
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; }
|
|
167
235
|
const el = document.createElement('div');
|
|
168
236
|
if (e.role === 'agent') {
|
|
169
237
|
el.className = 'msg agent';
|
|
170
|
-
el.innerHTML =
|
|
171
|
-
|
|
172
|
-
if (!chatOpen()) $('unread').hidden = false;
|
|
238
|
+
el.innerHTML = md(e.text);
|
|
239
|
+
if (live && !panelOpen()) { state.unread = true; renderBadge(); }
|
|
173
240
|
} else {
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
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>` : '');
|
|
183
257
|
}
|
|
184
258
|
msgsEl.appendChild(el);
|
|
259
|
+
renderWorking();
|
|
185
260
|
if (scroll) scrollChat();
|
|
186
261
|
}
|
|
187
262
|
const scrollChat = () => { msgsEl.scrollTop = msgsEl.scrollHeight; };
|
|
@@ -192,49 +267,82 @@
|
|
|
192
267
|
const [page] = a.dataset.page.split('#');
|
|
193
268
|
if (state.pages.some((p) => p.page === page)) go(page);
|
|
194
269
|
});
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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>`);
|
|
200
275
|
}
|
|
201
276
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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(); }
|
|
210
298
|
};
|
|
211
|
-
|
|
212
|
-
}
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
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>`;
|
|
221
318
|
}
|
|
222
|
-
|
|
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();
|
|
223
334
|
}
|
|
224
335
|
|
|
336
|
+
// ---------- sending ----------
|
|
225
337
|
async function send(text, extra = {}) {
|
|
226
338
|
text = String(text || '').trim();
|
|
227
|
-
const
|
|
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 }));
|
|
228
342
|
if (!text && !context.length && !extra.answer) return;
|
|
229
343
|
const r = await api('/api/send', { text, context, page: state.page, ...extra });
|
|
230
344
|
if (r.id && !r.delivered) { state.pending.add(r.id); markPending(r.id, true); }
|
|
231
|
-
if (
|
|
232
|
-
}
|
|
233
|
-
function markPending(id, on) {
|
|
234
|
-
const el = msgsEl.querySelector(`.msg[data-id="${CSS.escape(id)}"] .meta`);
|
|
235
|
-
if (!el) return;
|
|
236
|
-
el.querySelector('.pending')?.remove();
|
|
237
|
-
if (on) el.insertAdjacentHTML('afterbegin', `<span class="pending">${S.queued}</span>`);
|
|
345
|
+
if (withNotes && notes.length && r.id) { state.notes = []; renderNotes(); syncFrameNotes(); }
|
|
238
346
|
}
|
|
239
347
|
|
|
240
348
|
const autosize = () => { input.style.height = 'auto'; input.style.height = Math.min(input.scrollHeight, 180) + 'px'; };
|
|
@@ -245,80 +353,104 @@
|
|
|
245
353
|
$('composer').addEventListener('submit', (e) => {
|
|
246
354
|
e.preventDefault();
|
|
247
355
|
const text = input.value;
|
|
248
|
-
if (!text.trim() && !state.
|
|
356
|
+
if (!text.trim() && !state.notes.length) { input.focus(); return; }
|
|
249
357
|
input.value = ''; autosize();
|
|
250
358
|
send(text);
|
|
251
359
|
});
|
|
252
|
-
input.placeholder = S.placeholder;
|
|
253
360
|
|
|
254
|
-
$('drawBlueprint').onclick = () => {
|
|
361
|
+
$('drawBlueprint').onclick = () => { setPanel(true); send(S.drawPrompt, { context: [], noNotes: true }); };
|
|
255
362
|
$('checkChip').onclick = () => {
|
|
256
363
|
const r = resultFor(state.page);
|
|
257
364
|
if (!r || (!r.counts.changed && !r.counts.broken)) return;
|
|
258
|
-
|
|
259
|
-
send(S.fixPrompt(`.truemap/${state.page}`, r.counts.changed, r.counts.broken), { context: [] });
|
|
365
|
+
setPanel(true);
|
|
366
|
+
send(S.fixPrompt(`.truemap/${state.page}`, r.counts.changed, r.counts.broken), { context: [], noNotes: true });
|
|
260
367
|
};
|
|
261
368
|
|
|
262
369
|
// A decision only counts as the user's if the user actually moved focus into the page.
|
|
263
370
|
window.addEventListener('blur', () => { setTimeout(() => { if (document.activeElement === frame) state.frameFocusAt = Date.now(); }, 0); });
|
|
264
371
|
const userIsInFrame = () => document.activeElement === frame && state.frameFocusAt > 0;
|
|
265
372
|
|
|
266
|
-
// ---------- messages from the page
|
|
373
|
+
// ---------- messages from the page frame ----------
|
|
267
374
|
window.addEventListener('message', (e) => {
|
|
268
375
|
if (e.source !== frame.contentWindow || e.origin !== CONTENT || !e.data || !e.data.__truemap) return;
|
|
269
376
|
const d = e.data;
|
|
270
377
|
if (d.type === 'loaded') {
|
|
271
378
|
if (d.page && d.page !== state.page) setCurrent(d.page);
|
|
272
379
|
renderHeader(); sendMarks();
|
|
380
|
+
if (!state.annotateTouched && typeof d.annotate === 'boolean') state.annotate = d.annotate;
|
|
381
|
+
setAnnotate(state.annotate);
|
|
382
|
+
syncFrameNotes();
|
|
273
383
|
const y = state.scroll[d.page]; if (y) toFrame({ type: 'scroll', y });
|
|
274
384
|
} else if (d.type === 'scroll') {
|
|
275
385
|
state.scroll[d.page] = d.y;
|
|
276
|
-
} else if (d.type === '
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
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 });
|
|
283
400
|
} else if (d.type === 'answer') {
|
|
284
401
|
const fromUser = d.trusted === true && userIsInFrame();
|
|
285
402
|
send('', {
|
|
286
|
-
kind: 'answer', from: fromUser ? 'user' : 'page',
|
|
403
|
+
kind: 'answer', from: fromUser ? 'user' : 'page', noNotes: true,
|
|
287
404
|
context: d.src ? [{ kind: 'element', label: d.question, src: d.src }] : [],
|
|
288
405
|
answer: { question: d.question, choice: d.choice, note: d.note },
|
|
289
406
|
});
|
|
290
407
|
} else if (d.type === 'page-send') {
|
|
291
|
-
if (d.text) send(d.text, { from: 'page', context: [],
|
|
408
|
+
if (d.text) send(d.text, { from: 'page', context: [], noNotes: true });
|
|
292
409
|
}
|
|
293
410
|
});
|
|
294
411
|
|
|
295
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
|
+
}
|
|
296
421
|
function connect() {
|
|
297
422
|
const es = new EventSource(`/api/events?t=${encodeURIComponent(TOKEN)}`);
|
|
298
423
|
let greeted = false;
|
|
299
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
|
+
};
|
|
300
429
|
es.onmessage = (ev) => {
|
|
301
430
|
let d; try { d = JSON.parse(ev.data); } catch { return; }
|
|
302
431
|
if (d.type === 'hello') {
|
|
303
|
-
greeted = true; clearTimeout(guard);
|
|
432
|
+
greeted = true; clearTimeout(guard); clearTimeout(closedTimer); closedTimer = null;
|
|
433
|
+
setConn('live');
|
|
304
434
|
state.pages = d.pages || []; state.check = d.check || { results: [] }; state.history = d.history || [];
|
|
305
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)); }
|
|
306
438
|
$('ver').textContent = `truemap ${d.version}`;
|
|
307
439
|
$('project').textContent = String(d.root || '').split(/[\\/]/).filter(Boolean).pop() || '';
|
|
308
|
-
|
|
309
|
-
renderAll();
|
|
440
|
+
state.agent = { state: d.agent?.state || 'offline', name: d.agent?.name || '', since: d.agent?.since || 0 };
|
|
441
|
+
renderAll(); renderAgent(); renderNotes();
|
|
310
442
|
const fromHash = decodeURIComponent((location.hash.match(/page=([^&]+)/) || [])[1] || '');
|
|
311
443
|
const target = [state.page, fromHash, d.current].find((p) => p && state.pages.some((x) => x.page === p)) || state.pages[0]?.page;
|
|
312
444
|
target ? go(target, { force: !frame.getAttribute('src') }) : showEmpty();
|
|
313
445
|
} else if (d.type === 'chat') {
|
|
314
|
-
state.history.push(d.entry); appendEntry(d.entry);
|
|
446
|
+
state.history.push(d.entry); appendEntry(d.entry, true, true);
|
|
447
|
+
if (d.entry.role === 'agent') state.lastAgentEvent = Date.now();
|
|
315
448
|
} else if (d.type === 'agent') {
|
|
316
|
-
setAgent(d.
|
|
317
|
-
if (d.state !== 'working') $('progress').hidden = true;
|
|
449
|
+
setAgent(d.agent);
|
|
318
450
|
} else if (d.type === 'delivered') {
|
|
319
451
|
for (const id of d.ids || []) { state.pending.delete(id); markPending(id, false); }
|
|
320
452
|
} else if (d.type === 'progress') {
|
|
321
|
-
|
|
453
|
+
state.progress = d.text || ''; state.lastAgentEvent = Date.now(); renderWorking(); renderNotice(); scrollChat();
|
|
322
454
|
} else if (d.type === 'pages') {
|
|
323
455
|
state.pages = d.pages || []; renderHeader(); if (!menu.hidden) renderMenu();
|
|
324
456
|
if (!state.page && state.pages[0]) go(state.pages[0].page);
|
|
@@ -330,10 +462,15 @@
|
|
|
330
462
|
state.check = d.check || { results: [] }; renderHeader(); sendMarks(); if (!menu.hidden) renderMenu();
|
|
331
463
|
} else if (d.type === 'navigate') {
|
|
332
464
|
if (d.pages) state.pages = d.pages;
|
|
465
|
+
if (typeof d.annotate === 'boolean') { state.annotate = d.annotate; state.annotateTouched = true; }
|
|
333
466
|
if (d.page && state.pages.some((p) => p.page === d.page)) go(d.page, { force: true });
|
|
467
|
+
else setAnnotate(state.annotate);
|
|
334
468
|
renderHeader();
|
|
469
|
+
} else if (d.type === 'closing') {
|
|
470
|
+
es.close(); setConn('closed');
|
|
335
471
|
}
|
|
336
472
|
};
|
|
337
473
|
}
|
|
474
|
+
renderNotes();
|
|
338
475
|
connect();
|
|
339
476
|
})();
|