@picassohq/cli 1.0.9 → 1.0.10

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.
@@ -11,17 +11,326 @@
11
11
  * the stream is reopened on pageshow/visibilitychange and when it has been silent for 20 s (heartbeats come every 15 s).
12
12
  *
13
13
  * The page runs under `default-src 'none'; script-src 'self'; style-src 'self'`: no inline handlers or styles. Every
14
- * value that reaches innerHTML goes through esc(); clicks are handled by one delegated listener on data-act attributes.
14
+ * value that reaches innerHTML goes through esc() (the markdown renderer below escapes its whole input first and only
15
+ * ever adds its own fixed tags); clicks are handled by one delegated listener on data-act attributes.
15
16
  */
17
+
18
+ /* ---------- markdown (begin) ----------
19
+ * A small, safe markdown renderer for model replies. No dependency, no CDN. It escapes every piece of source text and
20
+ * builds HTML only from a fixed set of tags (p, h1-h6, strong, em, del, code, pre, ul, ol, li, blockquote, hr, br,
21
+ * table parts, a, and its own div/span/button wrappers). Raw HTML from the model is shown as text, never parsed.
22
+ * Links keep http, https and mailto URLs only (anything else is shown as its label text) and always open in a new tab
23
+ * with rel="noopener noreferrer". Images are never loaded; they become links. Self-contained (no outside names) so
24
+ * test/remote-markdown.test.ts can run this block on its own. */
25
+ const RemoteMarkdown = (() => {
26
+ 'use strict';
27
+ const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
28
+ const NUL = '\u0000';
29
+ const MAX_DEPTH = 8;
30
+ const FENCE = /^( {0,3})(`{3,}|~{3,})[ \t]*([^\s`]*)[^`]*$/;
31
+ const FENCE_CLOSE = /^ {0,3}(`{3,}|~{3,})[ \t]*$/;
32
+ const HEADING = /^ {0,3}(#{1,6})(?:[ \t]+(.*?))?(?:[ \t]+#+)?[ \t]*$/;
33
+ const HR = /^ {0,3}(?:(?:-[ \t]*){3,}|(?:\*[ \t]*){3,}|(?:_[ \t]*){3,})$/;
34
+ const QUOTE = /^ {0,3}>[ \t]?(.*)$/;
35
+ const LIST = /^([ \t]*)([-*+]|\d{1,9}[.)])(?:[ \t]+(.*)|[ \t]*)$/;
36
+ const DELIM = /^[ \t]*\|?[ \t]*:?-+:?[ \t]*(?:\|[ \t]*:?-+:?[ \t]*)*\|?[ \t]*$/;
37
+ const TASK = /^\[([ xX])\][ \t]+/;
38
+ const indentOf = (line) => /^[ \t]*/.exec(line)[0].length;
39
+
40
+ /** An http(s) URL with a host, or a mailto: address; anything else (javascript:, data:, relative paths, control
41
+ characters, whitespace) is refused and returns ''. */
42
+ function safeHref(raw) {
43
+ const url = String(raw ?? '').trim();
44
+ if (!url || /[\u0000- \u007f<>"'`\\]/.test(url)) return '';
45
+ if (/^https?:\/\/[^/?#\s@]*[a-z0-9\]]/i.test(url)) return url;
46
+ if (/^mailto:[^\s/?#][^\s]*@[^\s]+$/i.test(url)) return url;
47
+ return '';
48
+ }
49
+
50
+ const anchor = (href, labelHtml, title) =>
51
+ `<a href="${esc(href)}" target="_blank" rel="noopener noreferrer"${title ? ` title="${esc(title)}"` : ''}>${labelHtml}</a>`;
52
+
53
+ /** Emphasis over already-escaped text (it can only wrap escaped text in fixed tags). */
54
+ function emphasis(s) {
55
+ return s
56
+ .replace(/\*\*(?=\S)([\s\S]*?\S)\*\*/g, '<strong>$1</strong>')
57
+ .replace(/(^|[^\w])__(?=\S)([\s\S]*?\S)__(?!\w)/g, '$1<strong>$2</strong>')
58
+ .replace(/(^|[^*\w])\*(?=[^\s*])([^*\n]*?[^\s*])\*(?![*\w])/g, '$1<em>$2</em>')
59
+ .replace(/(^|[^\w])_(?=[^\s_])([^_\n]*?[^\s_])_(?!\w)/g, '$1<em>$2</em>')
60
+ .replace(/~~(?=\S)([\s\S]*?\S)~~/g, '<del>$1</del>');
61
+ }
62
+
63
+ /** Inline markdown in one block of text: code spans, escapes, links, autolinks, emphasis. */
64
+ function inline(text) {
65
+ const slots = [];
66
+ const put = (html) => `${NUL}${slots.push(html) - 1}${NUL}`;
67
+ let s = String(text ?? '').replace(/\u0000/g, '');
68
+ s = s.replace(/\\`/g, () => put('`')); // an escaped backtick never opens a code span
69
+ s = s.replace(/(`+)([^`]|[^`][\s\S]*?[^`])\1(?!`)/g, (_, _ticks, body) => {
70
+ const code = /^ [\s\S]* $/.test(body) && body.trim() ? body.slice(1, -1) : body;
71
+ return put(`<code>${esc(code)}</code>`);
72
+ });
73
+ s = s.replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g, (_, c) => put(esc(c)));
74
+ s = s.replace(/<((?:https?:\/\/|mailto:)[^\s<>]+)>/gi, (all, url) => {
75
+ const href = safeHref(url);
76
+ return href ? put(anchor(href, esc(url))) : all;
77
+ });
78
+ s = s.replace(/(!?)\[((?:[^[\]\n]|\[[^[\]\n]*\])*)\]\([ \t]*<?([^\s<>()]*(?:\([^\s<>()]*\)[^\s<>()]*)*)>?(?:[ \t]+(?:"([^"\n]*)"|'([^'\n]*)'))?[ \t]*\)/g,
79
+ (_, bang, label, url, t1, t2) => {
80
+ const href = safeHref(url);
81
+ const labelHtml = emphasis(esc(label)) || esc(bang ? 'image' : url);
82
+ if (!href) return put(`<span class="md-badlink">${labelHtml}</span>`);
83
+ return put(anchor(href, labelHtml, t1 ?? t2));
84
+ });
85
+ s = s.replace(/\bhttps?:\/\/[^\s<>"'`\u0000]+/gi, (url) => {
86
+ let tail = '';
87
+ let core = url;
88
+ for (;;) {
89
+ const last = core.slice(-1);
90
+ if (/[.,;:!?*_~]/.test(last)) { tail = last + tail; core = core.slice(0, -1); continue; }
91
+ if (last === ')' && (core.match(/\(/g) || []).length < (core.match(/\)/g) || []).length) { tail = last + tail; core = core.slice(0, -1); continue; }
92
+ break;
93
+ }
94
+ const href = safeHref(core);
95
+ return href ? put(anchor(href, esc(core))) + tail : url;
96
+ });
97
+ s = emphasis(esc(s));
98
+ for (let guard = 0; s.includes(NUL) && guard < 8; guard += 1) s = s.replace(/\u0000(\d+)\u0000/g, (_, n) => slots[Number(n)] ?? '');
99
+ return s.replace(/\u0000/g, '');
100
+ }
101
+
102
+ const isTableStart = (lines, i) => lines[i].includes('|') && i + 1 < lines.length && DELIM.test(lines[i + 1]) && lines[i + 1].includes('-')
103
+ && splitRow(lines[i]).length === splitRow(lines[i + 1]).length;
104
+
105
+ function isBlockStart(lines, i) {
106
+ const line = lines[i];
107
+ return !line.trim() || FENCE.test(line) || HEADING.test(line) || HR.test(line) || QUOTE.test(line) || LIST.test(line) || isTableStart(lines, i);
108
+ }
109
+
110
+ /** A table row's cells: split on pipes outside code spans, `\|` kept as a pipe. */
111
+ function splitRow(line) {
112
+ let s = line.trim();
113
+ if (s.startsWith('|')) s = s.slice(1);
114
+ if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1);
115
+ const cells = [];
116
+ let cur = '';
117
+ let ticks = 0;
118
+ for (let i = 0; i < s.length; i += 1) {
119
+ const c = s[i];
120
+ if (c === '\\' && s[i + 1] === '|') { cur += '\\|'; i += 1; continue; }
121
+ if (c === '`') {
122
+ let run = 1;
123
+ while (s[i + run] === '`') run += 1;
124
+ if (ticks === 0) ticks = run; else if (ticks === run) ticks = 0;
125
+ cur += s.slice(i, i + run); i += run - 1; continue;
126
+ }
127
+ if (c === '|' && ticks === 0) { cells.push(cur.trim()); cur = ''; continue; }
128
+ cur += c;
129
+ }
130
+ cells.push(cur.trim());
131
+ return cells;
132
+ }
133
+
134
+ function table(lines, i) {
135
+ const head = splitRow(lines[i]);
136
+ const align = splitRow(lines[i + 1]).map((d) => (/^:-+:$/.test(d) ? ' class="al-c"' : /-:$/.test(d) ? ' class="al-r"' : ''));
137
+ const rows = [];
138
+ let j = i + 2;
139
+ while (j < lines.length && lines[j].trim() && lines[j].includes('|') && !FENCE.test(lines[j]) && !QUOTE.test(lines[j]) && !HEADING.test(lines[j])) {
140
+ rows.push(splitRow(lines[j]));
141
+ j += 1;
142
+ }
143
+ const cell = (tag, cells) => head.map((_, k) => `<${tag}${align[k] || ''}>${inline((cells[k] ?? '').replace(/\\\|/g, '|'))}</${tag}>`).join('');
144
+ const html = `<div class="md-table"><table><thead><tr>${cell('th', head)}</tr></thead>`
145
+ + `${rows.length ? `<tbody>${rows.map((r) => `<tr>${cell('td', r)}</tr>`).join('')}</tbody>` : ''}</table></div>`;
146
+ return { html, next: j };
147
+ }
148
+
149
+ function codeBlock(code, lang) {
150
+ const name = /^[\w+#.-]{1,24}$/.test(lang) ? lang : '';
151
+ return `<div class="md-code"><div class="md-code-bar"><span class="md-lang">${esc(name || 'code')}</span>`
152
+ + '<button type="button" class="md-copy" data-act="copy" aria-label="Copy code">Copy</button></div>'
153
+ + `<pre><code>${esc(code)}</code></pre></div>`;
154
+ }
155
+
156
+ function list(lines, start, depth) {
157
+ const first = LIST.exec(lines[start]);
158
+ const base = first[1].length;
159
+ const ordered = /\d/.test(first[2]);
160
+ const from = ordered ? parseInt(first[2], 10) : 1;
161
+ const items = [];
162
+ let cur = null;
163
+ let i = start;
164
+ while (i < lines.length) {
165
+ const line = lines[i];
166
+ if (!line.trim()) {
167
+ let j = i + 1;
168
+ while (j < lines.length && !lines[j].trim()) j += 1;
169
+ if (j >= lines.length) { i = j; break; }
170
+ const nm = HR.test(lines[j]) ? null : LIST.exec(lines[j]);
171
+ const sameLevel = nm && nm[1].length >= base && nm[1].length <= base + 1 && /\d/.test(nm[2]) === ordered;
172
+ if (sameLevel || (cur && indentOf(lines[j]) >= cur.content)) { if (cur) cur.lines.push(''); i = j; continue; }
173
+ break;
174
+ }
175
+ const ind = indentOf(line);
176
+ const m = HR.test(line) ? null : LIST.exec(line);
177
+ if (m && ind <= base + 1 && (!cur || ind < cur.content)) {
178
+ if (ind < base || /\d/.test(m[2]) !== ordered) break;
179
+ cur = { lines: [m[3] || ''], content: ind + m[2].length + 1 };
180
+ items.push(cur);
181
+ i += 1;
182
+ continue;
183
+ }
184
+ if (cur && ind >= Math.min(cur.content, base + 2)) { cur.lines.push(line.slice(Math.min(ind, cur.content))); i += 1; continue; }
185
+ if (cur && !isBlockStart(lines, i)) { cur.lines.push(line.trim()); i += 1; continue; }
186
+ break;
187
+ }
188
+ const tag = ordered ? 'ol' : 'ul';
189
+ const body = items.map((item) => {
190
+ const task = TASK.exec(item.lines[0]);
191
+ if (task) item.lines[0] = item.lines[0].slice(task[0].length);
192
+ const box = task ? `<span class="md-task${task[1] === ' ' ? '' : ' done'}" aria-hidden="true"></span>` : '';
193
+ return `<li${task ? ' class="task"' : ''}>${box}${blocks(item.lines, depth + 1)}</li>`;
194
+ }).join('');
195
+ return { html: `<${tag}${ordered && from !== 1 ? ` start="${from}"` : ''}>${body}</${tag}>`, next: i };
196
+ }
197
+
198
+ function paragraph(text) {
199
+ return `<p>${inline(text).replace(/\n/g, '<br>')}</p>`;
200
+ }
201
+
202
+ function blocks(lines, depth) {
203
+ if (depth > MAX_DEPTH) return paragraph(lines.join('\n'));
204
+ let out = '';
205
+ let i = 0;
206
+ while (i < lines.length) {
207
+ const line = lines[i];
208
+ if (!line.trim()) { i += 1; continue; }
209
+ let m = FENCE.exec(line);
210
+ if (m) {
211
+ const indent = m[1].length;
212
+ const fence = m[2];
213
+ const body = [];
214
+ i += 1;
215
+ while (i < lines.length) {
216
+ const close = FENCE_CLOSE.exec(lines[i]);
217
+ if (close && close[1][0] === fence[0] && close[1].length >= fence.length) { i += 1; break; }
218
+ body.push(indent ? lines[i].replace(new RegExp(`^ {0,${indent}}`), '') : lines[i]);
219
+ i += 1;
220
+ }
221
+ out += codeBlock(body.join('\n'), m[3] || '');
222
+ continue;
223
+ }
224
+ if ((m = HEADING.exec(line))) {
225
+ const level = m[1].length;
226
+ out += `<h${level}>${inline(m[2] || '')}</h${level}>`;
227
+ i += 1;
228
+ continue;
229
+ }
230
+ if (HR.test(line)) { out += '<hr>'; i += 1; continue; }
231
+ if (QUOTE.test(line)) {
232
+ const inner = [];
233
+ while (i < lines.length && lines[i].trim()) {
234
+ const q = QUOTE.exec(lines[i]);
235
+ if (q) inner.push(q[1]);
236
+ else if (!isBlockStart(lines, i)) inner.push(lines[i]);
237
+ else break;
238
+ i += 1;
239
+ }
240
+ out += `<blockquote>${blocks(inner, depth + 1)}</blockquote>`;
241
+ continue;
242
+ }
243
+ if (isTableStart(lines, i)) {
244
+ const t = table(lines, i);
245
+ out += t.html;
246
+ i = t.next;
247
+ continue;
248
+ }
249
+ if (LIST.test(line)) {
250
+ const l = list(lines, i, depth);
251
+ out += l.html;
252
+ i = l.next;
253
+ continue;
254
+ }
255
+ const para = [line.replace(/^[ \t]+/, '')];
256
+ i += 1;
257
+ while (i < lines.length && !isBlockStart(lines, i)) { para.push(lines[i].replace(/^[ \t]+/, '')); i += 1; }
258
+ out += paragraph(para.join('\n'));
259
+ }
260
+ return out;
261
+ }
262
+
263
+ const lines = (text) => String(text ?? '').replace(/\u0000/g, '').replace(/\r\n?/g, '\n')
264
+ .split('\n').map((l) => l.replace(/^\t+/, (t) => ' '.repeat(t.length)));
265
+
266
+ /** Markdown → safe HTML. */
267
+ function render(text) {
268
+ return blocks(lines(text), 0);
269
+ }
270
+
271
+ /** Inline markdown → plain text (labels for links, contents for code, no markers). */
272
+ function plainInline(s) {
273
+ return s
274
+ .replace(/!?\[((?:[^[\]\n]|\[[^[\]\n]*\])*)\]\([^)\n]*\)/g, '$1')
275
+ .replace(/<((?:https?:\/\/|mailto:)[^\s<>]+)>/gi, '$1')
276
+ .replace(/(`+)([\s\S]*?[^`])\1(?!`)/g, (_, _t, body) => body.trim())
277
+ .replace(/(\*\*|__|~~)(?=\S)([\s\S]*?\S)\1/g, '$2')
278
+ .replace(/(^|[^*\w])\*(?=[^\s*])([^*\n]*?[^\s*])\*(?![*\w])/g, '$1$2')
279
+ .replace(/(^|[^\w])_(?=[^\s_])([^_\n]*?[^\s_])_(?!\w)/g, '$1$2')
280
+ .replace(/\\([!"#$%&'()*+,\-./:;<=>?@[\\\]^_`{|}~])/g, '$1');
281
+ }
282
+
283
+ /** Markdown → plain text lines (no `**`, `##`, backticks, list markers, quote marks or table rules). */
284
+ function plainLines(text) {
285
+ const out = [];
286
+ let fence = '';
287
+ for (const raw of lines(text)) {
288
+ const f = FENCE.exec(raw) || FENCE_CLOSE.exec(raw);
289
+ if (f && (!fence || (FENCE_CLOSE.test(raw) && raw.trim()[0] === fence))) { fence = fence ? '' : raw.trim()[0]; continue; }
290
+ if (fence) { if (raw.trim()) out.push(raw.trim()); continue; }
291
+ if (HR.test(raw) || (DELIM.test(raw) && raw.includes('-'))) continue;
292
+ let line = raw.replace(/^ {0,3}#{1,6}(?:[ \t]+|$)/, '').replace(/[ \t]+#+[ \t]*$/, '')
293
+ .replace(/^[ \t]*(?:>[ \t]?)+/, '')
294
+ .replace(/^[ \t]*(?:[-*+]|\d{1,9}[.)])[ \t]+(?:\[[ xX]\][ \t]+)?/, '');
295
+ if (/^\s*\|.*\|\s*$|\s\|\s/.test(line)) line = splitRow(line).filter(Boolean).join(', ');
296
+ line = plainInline(line).replace(/\s+/g, ' ').trim();
297
+ if (line) out.push(line);
298
+ }
299
+ return out;
300
+ }
301
+
302
+ /** Markdown → one line of plain text (a thread-list preview). */
303
+ function plain(text, max = 160) {
304
+ const s = plainLines(text).join(' ');
305
+ return s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s;
306
+ }
307
+
308
+ return { render, plain, plainLines, safeHref, esc };
309
+ })();
310
+ /* ---------- markdown (end) ---------- */
311
+
16
312
  (() => {
17
313
  'use strict';
18
314
 
19
315
  const STORE_KEY = 'picasso.remote';
20
316
  const STALE_AFTER_MS = 20_000;
21
317
  const MAX_EVENTS_PER_THREAD = 3_000;
318
+ const SCOPES = ['read', 'prompt', 'approve', 'stop'];
22
319
  const SCOPE_WORDS = { read: 'follow threads', prompt: 'send prompts', approve: 'answer approvals and questions', stop: 'stop turns' };
320
+ const SCOPE_LABELS = { read: 'Follow threads', prompt: 'Send prompts', approve: 'Answer approvals and questions', stop: 'Stop turns' };
23
321
  const UNREACHABLE = `Can't reach Picasso at ${location.host}. Check that the computer is awake and that this device is on the same network or tailnet.`;
24
322
 
323
+ /* Icons: fixed inline SVG markup (no values reach them). */
324
+ const ICON = {
325
+ back: '<svg viewBox="0 0 20 20" aria-hidden="true"><path d="M12.5 4.5 7 10l5.5 5.5" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>',
326
+ more: '<svg viewBox="0 0 20 20" aria-hidden="true"><circle cx="4.5" cy="10" r="1.6" fill="currentColor"/><circle cx="10" cy="10" r="1.6" fill="currentColor"/><circle cx="15.5" cy="10" r="1.6" fill="currentColor"/></svg>',
327
+ bell: '<svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 3.2a4.6 4.6 0 0 0-4.6 4.6v2.6L4 13.2h12l-1.4-2.8V7.8A4.6 4.6 0 0 0 10 3.2Zm-1.8 12.2a1.9 1.9 0 0 0 3.6 0" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linejoin="round"/></svg>',
328
+ plus: '<svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 4.5v11M4.5 10h11" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round"/></svg>',
329
+ send: '<svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 15.5v-11M5.2 9.3 10 4.5l4.8 4.8" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"/></svg>',
330
+ stop: '<svg viewBox="0 0 20 20" aria-hidden="true"><rect x="5.5" y="5.5" width="9" height="9" rx="1.5" fill="currentColor"/></svg>',
331
+ down: '<svg viewBox="0 0 20 20" aria-hidden="true"><path d="M10 4.5v11M5.2 10.7 10 15.5l4.8-4.8" fill="none" stroke="currentColor" stroke-width="1.8" stroke-linecap="round" stroke-linejoin="round"/></svg>',
332
+ };
333
+
25
334
  const $app = document.getElementById('app');
26
335
  window.addEventListener('error', (e) => fatal(e.error || e.message));
27
336
  window.addEventListener('unhandledrejection', (e) => fatal(e.reason));
@@ -43,6 +352,9 @@ const state = {
43
352
  paintQueued: false,
44
353
  synced: false, // a snapshot arrived on this page (until then the list says Loading or can't reach)
45
354
  unreachable: false, // the last stream attempt failed before any snapshot
355
+ open: new Set(), // keys of expanded <details> (tool calls, thinking), kept across repaints
356
+ stick: true, // the feed follows new output (the reader is at the bottom)
357
+ smoothUntil: 0,
46
358
  };
47
359
 
48
360
  function loadCred() {
@@ -61,7 +373,7 @@ function saveCred(c) {
61
373
  }
62
374
  function dropCred() { try { localStorage.removeItem(STORE_KEY); } catch { /* nothing stored */ } state.cred = null; }
63
375
 
64
- const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' })[c]);
376
+ const esc = RemoteMarkdown.esc;
65
377
  const fmtWhen = (ms) => {
66
378
  if (!ms) return '';
67
379
  const d = new Date(ms);
@@ -69,10 +381,25 @@ const fmtWhen = (ms) => {
69
381
  };
70
382
  const shortId = (id) => (id && id.length > 10 ? `${id.slice(0, 6)}…${id.slice(-4)}` : id || '');
71
383
  const can = (scope) => state.scopes.has(scope);
72
- const lastLine = (text) => { const lines = String(text || '').trim().split('\n'); return lines[lines.length - 1] || ''; };
384
+ const folderName = (cwd) => String(cwd || '').replace(/\/+$/, '').split('/').pop() || '';
385
+ /** The newest line of streaming text, as plain text (no markdown markers). */
386
+ const liveLine = (text) => RemoteMarkdown.plainLines(text).at(-1) || '';
387
+
388
+ /* Rendered markdown, cached by source text (a repaint re-renders only what changed). */
389
+ const mdCache = new Map();
390
+ function md(text) {
391
+ const key = String(text ?? '');
392
+ let html = mdCache.get(key);
393
+ if (html === undefined) {
394
+ html = RemoteMarkdown.render(key);
395
+ if (mdCache.size > 600) mdCache.clear();
396
+ mdCache.set(key, html);
397
+ }
398
+ return html;
399
+ }
73
400
 
74
401
  function setScopes(device) {
75
- const scopes = device && Array.isArray(device.scopes) ? device.scopes : ['read', 'prompt', 'approve', 'stop'];
402
+ const scopes = device && Array.isArray(device.scopes) ? device.scopes : SCOPES;
76
403
  state.scopes = new Set(scopes);
77
404
  }
78
405
 
@@ -113,7 +440,7 @@ function errorText(status, body) {
113
440
  let noticeTimer = null;
114
441
  function notice(text, isError = true) {
115
442
  let el = document.getElementById('notice');
116
- if (!el) { el = document.createElement('div'); el.id = 'notice'; document.body.appendChild(el); }
443
+ if (!el) { el = document.createElement('div'); el.id = 'notice'; el.setAttribute('role', 'status'); document.body.appendChild(el); }
117
444
  el.className = `notice${isError ? ' err' : ''}`;
118
445
  el.textContent = text;
119
446
  el.hidden = false;
@@ -135,13 +462,15 @@ function deviceName() {
135
462
 
136
463
  function signInScreen(code, message) {
137
464
  stopStream();
465
+ closeSheet();
138
466
  document.body.className = 'screen-signin';
139
467
  $app.innerHTML = `
140
468
  <main class="signin">
469
+ <div class="brand"><img src="/remote/icon.svg" alt="" width="40" height="40"><div class="brand-t">Picasso</div><div class="brand-s">Remote control</div></div>
141
470
  ${message ? `<div class="banner">${esc(message)}</div>` : ''}
142
471
  <div class="card">
143
- <div class="h">Remote control</div>
144
- <div class="p">Follow and steer Picasso threads on your computer from this device. Get a code from Settings › Remote on the Mac, or <code>picasso remote pair</code> in a terminal.</div>
472
+ <div class="h">Pair this device</div>
473
+ <div class="p">Follow and steer Picasso threads on your computer from here. Get a code from Settings › Remote on the Mac, or <code>picasso remote pair</code> in a terminal.</div>
145
474
  <div class="field">
146
475
  <label for="code">Pairing code</label>
147
476
  <input id="code" class="code" maxlength="10" autocapitalize="characters" autocorrect="off" spellcheck="false"
@@ -236,45 +565,80 @@ function signOut(message) {
236
565
 
237
566
  /* ---------- shell ---------- */
238
567
 
568
+ function listHeadHtml() {
569
+ return `<span class="lbl">Threads</span>${can('prompt') ? `<button class="btn newbtn" data-act="new">${ICON.plus}<span>New</span></button>` : ''}`;
570
+ }
571
+
239
572
  function shell() {
240
573
  $app.innerHTML = `
241
574
  <header class="bar">
242
- <button class="btn quiet" id="back" data-act="back" hidden>‹ Threads</button>
243
- <div class="who">
244
- <div class="title">Picasso</div>
245
- <div class="sub" id="devline"></div>
246
- </div>
247
- <span class="conn" id="conn">Connecting…</span>
248
- <button class="btn quiet" id="needsbtn" data-act="needs">Needs you</button>
249
- <button class="btn quiet" data-act="signout" title="Forget this device's token">Sign out</button>
575
+ <button class="iconbtn" id="back" data-act="back" hidden aria-label="Back to threads">${ICON.back}</button>
576
+ <div class="who"><span class="title" id="htitle">Picasso</span><span class="conn" id="conn" role="status">Connecting…</span></div>
577
+ <button class="needsbtn" id="needsbtn" data-act="needs" aria-label="Needs you">${ICON.bell}<span class="nlbl">Needs you</span></button>
578
+ <button class="iconbtn" id="menubtn" data-act="menu" aria-label="This device" aria-haspopup="dialog" aria-expanded="false">${ICON.more}</button>
250
579
  </header>
251
580
  <div class="panes">
252
581
  <aside id="listpane">
253
- <div class="listhead"><span class="lbl">Threads</span>${can('prompt') ? '<button class="btn" data-act="new">New</button>' : ''}</div>
582
+ <div class="listhead">${listHeadHtml()}</div>
254
583
  <div class="list" id="list"><div class="empty">Loading…</div></div>
255
584
  </aside>
256
585
  <section id="mainpane">
257
- <div id="threadview" hidden>
586
+ <div id="threadview" class="view" hidden>
258
587
  <div class="thead">
259
588
  <div class="tt"><div class="l1" id="ttitle"></div><div class="l2" id="tsub"></div></div>
260
- <button class="btn warn" id="stopbtn" data-act="stop" hidden>Stop</button>
589
+ <button class="btn stopbtn" id="stopbtn" data-act="stop" hidden>${ICON.stop}<span>Stop</span></button>
590
+ </div>
591
+ <div class="feedwrap">
592
+ <div class="feed" id="feed"></div>
593
+ <button class="jump" id="jump" data-act="jump" hidden>${ICON.down}<span>Jump to latest</span></button>
261
594
  </div>
262
- <div class="feed" id="feed"></div>
263
595
  <form class="composer" id="composer"${can('prompt') ? '' : ' hidden'}>
264
- <textarea id="prompt" rows="1" placeholder="Send to this thread…" enterkeyhint="send"></textarea>
265
- <button class="btn acc" id="send" type="submit">Send</button>
596
+ <textarea id="prompt" rows="1" placeholder="Send to this thread…" enterkeyhint="send" aria-label="Message"></textarea>
597
+ <button class="sendbtn" id="send" type="submit" disabled aria-label="Send">${ICON.send}</button>
266
598
  </form>
267
599
  </div>
268
- <div id="needsview" hidden><div class="thead"><div class="tt"><div class="l1">Needs you</div><div class="l2" id="needsub"></div></div></div><div class="feed" id="needs"></div></div>
600
+ <div id="needsview" class="view" hidden>
601
+ <div class="thead"><div class="tt"><div class="l1">Needs you</div><div class="l2" id="needsub"></div></div></div>
602
+ <div class="feedwrap"><div class="feed" id="needs"></div></div>
603
+ </div>
269
604
  <div id="placeholder" class="empty"><div class="big">Pick a thread</div>Replies stream here as they are written.</div>
270
605
  </section>
606
+ </div>
607
+ <div class="sheetwrap" id="sheet" hidden>
608
+ <div class="scrim" data-act="menu-close"></div>
609
+ <div class="sheet" role="dialog" aria-modal="true" aria-labelledby="sheettitle">
610
+ <div class="grab" aria-hidden="true"></div>
611
+ <div class="sheet-h" id="sheettitle">This device</div>
612
+ <div class="kv"><span class="k">Name</span><span class="v" id="devline"></span></div>
613
+ <div class="kv"><span class="k">Connection</span><span class="v" id="connline"></span></div>
614
+ <div class="sheet-sub">Allowed from here</div>
615
+ <ul class="perms" id="perms"></ul>
616
+ <button class="btn danger full" data-act="signout">Sign out</button>
617
+ <div class="fine">Signing out forgets this device's token. Pair again from the computer to come back.</div>
618
+ <button class="btn full" data-act="menu-close">Done</button>
619
+ </div>
271
620
  </div>`;
272
621
  const ta = document.getElementById('prompt');
622
+ const send = document.getElementById('send');
273
623
  document.getElementById('composer').addEventListener('submit', (e) => { e.preventDefault(); void sendPrompt(); });
274
624
  ta.addEventListener('keydown', (e) => {
275
625
  if (e.key === 'Enter' && !e.shiftKey && !e.isComposing && !matchMedia('(pointer: coarse)').matches) { e.preventDefault(); void sendPrompt(); }
276
626
  });
277
- ta.addEventListener('input', () => { ta.rows = Math.min(6, Math.max(1, ta.value.split('\n').length)); });
627
+ ta.addEventListener('input', () => { fitComposer(); send.disabled = !ta.value.trim() || sending; });
628
+ const feed = document.getElementById('feed');
629
+ feed.addEventListener('scroll', () => {
630
+ if (Date.now() < state.smoothUntil) return; // a jump-to-latest glide is still on its way down
631
+ state.stick = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 80;
632
+ document.getElementById('jump').hidden = state.stick;
633
+ }, { passive: true });
634
+ }
635
+
636
+ /** The composer grows with its text up to six lines (CSSOM height: allowed under the page's CSP). */
637
+ function fitComposer() {
638
+ const ta = document.getElementById('prompt');
639
+ if (!ta) return;
640
+ ta.style.height = 'auto';
641
+ if (ta.value) ta.style.height = `${Math.min(ta.scrollHeight + 2, 160)}px`;
278
642
  }
279
643
 
280
644
  $app.addEventListener('click', (e) => {
@@ -284,18 +648,67 @@ $app.addEventListener('click', (e) => {
284
648
  switch (act) {
285
649
  case 'pair': void pairWith(document.getElementById('code').value); return;
286
650
  case 'token': void signInWithToken(document.getElementById('tokenin').value); return;
287
- case 'signout': signOut(''); return;
651
+ case 'signout': closeSheet(); signOut(''); return;
288
652
  case 'back': showList(); return;
289
- case 'needs': showNeeds(); return;
653
+ case 'needs': if (state.screen === 'needs') showList(); else showNeeds(); return;
654
+ case 'menu': openSheet(); return;
655
+ case 'menu-close': closeSheet(); return;
290
656
  case 'open': openThread(target.dataset.id); return;
291
657
  case 'new': openThread(''); return;
292
658
  case 'stop': void stopTurn(target); return;
293
659
  case 'earlier': void loadHistory(state.threadId, true); return;
660
+ case 'jump': scrollFeed(true); return;
661
+ case 'copy': void copyCode(target); return;
294
662
  case 'allow': case 'allow-session': case 'deny': case 'answer': case 'decline':
295
663
  void decide(target, act); return;
296
664
  default:
297
665
  }
298
666
  });
667
+ // Rows are role="button" divs: Enter and Space open them as a click does.
668
+ $app.addEventListener('keydown', (e) => {
669
+ if ((e.key === 'Enter' || e.key === ' ') && e.target instanceof Element && e.target.matches('[role="button"][data-act]')) { e.preventDefault(); e.target.click(); }
670
+ });
671
+ // <details> (tool calls, thinking) keep their open state across repaints. `toggle` does not bubble: capture it.
672
+ $app.addEventListener('toggle', (e) => {
673
+ const d = e.target;
674
+ if (!(d instanceof HTMLDetailsElement) || !d.dataset.ok) return;
675
+ if (d.open) state.open.add(d.dataset.ok); else state.open.delete(d.dataset.ok);
676
+ }, true);
677
+ document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeSheet(); });
678
+
679
+ function openSheet() {
680
+ const sheet = document.getElementById('sheet');
681
+ if (!sheet) return;
682
+ paintSheet();
683
+ sheet.hidden = false;
684
+ document.getElementById('menubtn').setAttribute('aria-expanded', 'true');
685
+ requestAnimationFrame(() => sheet.classList.add('in'));
686
+ }
687
+ function closeSheet() {
688
+ const sheet = document.getElementById('sheet');
689
+ if (!sheet || sheet.hidden) return;
690
+ sheet.classList.remove('in');
691
+ sheet.hidden = true;
692
+ document.getElementById('menubtn')?.setAttribute('aria-expanded', 'false');
693
+ }
694
+
695
+ async function copyCode(btn) {
696
+ const pre = btn.closest('.md-code')?.querySelector('pre');
697
+ if (!pre) return;
698
+ const text = pre.textContent || '';
699
+ let ok = false;
700
+ try { await navigator.clipboard.writeText(text); ok = true; } catch {
701
+ // Older browsers and plain-http pages have no async clipboard: a hidden selection and execCommand still work.
702
+ const ta = document.createElement('textarea');
703
+ ta.value = text; ta.setAttribute('readonly', ''); ta.className = 'offscreen';
704
+ document.body.appendChild(ta); ta.select();
705
+ try { ok = document.execCommand('copy'); } catch { ok = false; }
706
+ ta.remove();
707
+ }
708
+ btn.textContent = ok ? 'Copied' : 'Copy failed';
709
+ btn.classList.toggle('done', ok);
710
+ setTimeout(() => { btn.textContent = 'Copy'; btn.classList.remove('done'); }, 1_600);
711
+ }
299
712
 
300
713
  function setScreen(screen) {
301
714
  state.screen = screen;
@@ -310,12 +723,43 @@ function showNeeds() { state.threadId = null; setScreen('needs'); }
310
723
 
311
724
  function openThread(id) {
312
725
  state.threadId = id;
726
+ state.stick = true;
727
+ const feed = document.getElementById('feed');
728
+ if (feed) feed.replaceChildren();
313
729
  setScreen('thread');
314
730
  const ta = document.getElementById('prompt');
315
- if (ta) { ta.value = ''; ta.placeholder = id ? 'Send to this thread…' : 'Start a new thread…'; }
731
+ if (ta) { ta.value = ''; ta.placeholder = id ? 'Send to this thread…' : 'Start a new thread…'; fitComposer(); }
732
+ const send = document.getElementById('send');
733
+ if (send) send.disabled = true;
316
734
  if (id && !thread(id).loaded) void loadHistory(id, false);
317
735
  }
318
736
 
737
+ /* iOS Safari keeps fixed and sticky elements on the layout viewport, behind the keyboard. The app shell follows the
738
+ visual viewport instead, so the composer sits right above the keyboard. Skipped while pinch-zoomed. */
739
+ function fitViewport() {
740
+ const vv = window.visualViewport;
741
+ const root = document.documentElement;
742
+ if (!vv || Math.abs(vv.scale - 1) > 0.01) { root.style.removeProperty('--app-h'); root.style.removeProperty('--app-top'); return; }
743
+ root.style.setProperty('--app-h', `${Math.round(vv.height)}px`);
744
+ root.style.setProperty('--app-top', `${Math.round(vv.offsetTop)}px`);
745
+ root.classList.toggle('kb', window.innerHeight - vv.height > 120);
746
+ if (state.stick) scrollFeed(false);
747
+ }
748
+ window.visualViewport?.addEventListener('resize', fitViewport);
749
+ window.visualViewport?.addEventListener('scroll', fitViewport);
750
+
751
+ function scrollFeed(smooth) {
752
+ const feed = document.getElementById('feed');
753
+ if (!feed) return;
754
+ state.stick = true;
755
+ const jump = document.getElementById('jump');
756
+ if (jump) jump.hidden = true;
757
+ if (smooth && !matchMedia('(prefers-reduced-motion: reduce)').matches) {
758
+ state.smoothUntil = Date.now() + 700;
759
+ feed.scrollTo({ top: feed.scrollHeight, behavior: 'smooth' });
760
+ } else feed.scrollTop = feed.scrollHeight;
761
+ }
762
+
319
763
  /* ---------- live stream ---------- */
320
764
 
321
765
  function streamUrl() {
@@ -387,13 +831,19 @@ setInterval(() => {
387
831
  if (state.cred && state.es && Date.now() - state.lastEventAt > STALE_AFTER_MS) { setConn('reconnecting'); wake(); }
388
832
  }, 5_000);
389
833
 
834
+ const CONN_TEXT = { live: 'Live', reconnecting: 'Reconnecting…', connecting: 'Connecting…' };
390
835
  function setConn(conn) {
391
836
  state.conn = conn;
392
837
  if (conn === 'live') state.retry = 0;
393
838
  const el = document.getElementById('conn');
394
839
  if (!el) return;
395
840
  el.className = `conn ${conn}`;
396
- el.textContent = conn === 'live' ? 'Live' : conn === 'reconnecting' ? 'Reconnecting…' : 'Connecting…';
841
+ el.textContent = CONN_TEXT[conn] || CONN_TEXT.connecting;
842
+ const line = document.getElementById('connline');
843
+ if (line) line.textContent = connLine();
844
+ }
845
+ function connLine() {
846
+ return state.conn === 'live' ? `Live with ${location.host}` : state.conn === 'reconnecting' ? `Reconnecting to ${location.host}…` : `Connecting to ${location.host}…`;
397
847
  }
398
848
 
399
849
  function onFrame(name, d) {
@@ -494,7 +944,7 @@ function addEvent(id, event, fromHistory = false) {
494
944
  t.liveText = ''; t.liveThink = '';
495
945
  const text = ((d.message && d.message.content) || []).filter((b) => b.type === 'text').map((b) => b.text).join('');
496
946
  const row = state.rows.get(id);
497
- if (text && row) row.lastReplyPreview = lastLine(text);
947
+ if (text && row) row.lastReplyPreview = text;
498
948
  break;
499
949
  }
500
950
  case 'session/title': { const row = state.rows.get(id); if (row && d.title) row.title = d.title; break; }
@@ -551,11 +1001,13 @@ async function loadHistory(id, earlier) {
551
1001
 
552
1002
  /* ---------- actions ---------- */
553
1003
 
1004
+ let sending = false;
554
1005
  async function sendPrompt() {
555
1006
  const ta = document.getElementById('prompt');
556
1007
  const text = ta.value.trim();
557
- if (!text || !can('prompt')) return;
1008
+ if (!text || !can('prompt') || sending) return;
558
1009
  const send = document.getElementById('send');
1010
+ sending = true;
559
1011
  send.disabled = true;
560
1012
  try {
561
1013
  let id = state.threadId;
@@ -569,11 +1021,13 @@ async function sendPrompt() {
569
1021
  }
570
1022
  await api(`/threads/${encodeURIComponent(id)}/prompt`, { method: 'POST', body: JSON.stringify({ text, mode: 'queue' }) });
571
1023
  ta.value = '';
572
- ta.rows = 1;
1024
+ fitComposer();
1025
+ state.stick = true;
573
1026
  } catch (e) {
574
1027
  if (e.message !== 'unpaired') notice(`Not sent: ${e.message}`);
575
1028
  } finally {
576
- send.disabled = false;
1029
+ sending = false;
1030
+ send.disabled = !ta.value.trim();
577
1031
  schedulePaint();
578
1032
  }
579
1033
  }
@@ -627,18 +1081,50 @@ function applyScopes() {
627
1081
  const composer = document.getElementById('composer');
628
1082
  if (composer) composer.hidden = !can('prompt');
629
1083
  const head = document.querySelector('.listhead');
630
- if (head) head.innerHTML = `<span class="lbl">Threads</span>${can('prompt') ? '<button class="btn" data-act="new">New</button>' : ''}`;
1084
+ if (head) head.innerHTML = listHeadHtml();
1085
+ paintSheet();
1086
+ }
1087
+
1088
+ /**
1089
+ * Keyed patch of `parent`'s children from `parts` ([{k, h}], each `h` one escaped root element): an unchanged part keeps
1090
+ * its element (and so its scroll position, open state and focus), a changed one is replaced, the rest are removed.
1091
+ */
1092
+ function patch(parent, parts) {
1093
+ const old = new Map();
1094
+ for (const el of [...parent.children]) { if (el.dataset.k && !old.has(el.dataset.k)) old.set(el.dataset.k, el); else el.remove(); }
1095
+ let prev = null;
1096
+ for (const { k, h } of parts) {
1097
+ let el = old.get(k);
1098
+ if (el && el.__h === h) old.delete(k);
1099
+ else {
1100
+ const tpl = document.createElement('template');
1101
+ tpl.innerHTML = h;
1102
+ const fresh = tpl.content.firstElementChild || document.createElement('div');
1103
+ fresh.dataset.k = k;
1104
+ fresh.__h = h;
1105
+ for (const d of [fresh, ...fresh.querySelectorAll('details[data-ok]')]) if (d instanceof HTMLDetailsElement && d.dataset.ok) d.open = state.open.has(d.dataset.ok);
1106
+ if (el) { el.replaceWith(fresh); old.delete(k); }
1107
+ el = fresh;
1108
+ }
1109
+ const want = prev ? prev.nextElementSibling : parent.firstElementChild;
1110
+ if (want !== el) parent.insertBefore(el, want);
1111
+ prev = el;
1112
+ }
1113
+ for (const el of old.values()) el.remove();
631
1114
  }
632
1115
 
633
1116
  function paint() {
634
1117
  if (!state.cred || !document.getElementById('list')) return;
635
- const dev = document.getElementById('devline');
636
- if (dev) dev.textContent = `${state.cred.device.name || 'This device'} · ${['read', 'prompt', 'approve', 'stop'].filter(can).join(', ') || 'no access'}`;
637
1118
  const needsBtn = document.getElementById('needsbtn');
638
1119
  if (needsBtn) {
639
- needsBtn.className = `btn quiet${state.screen === 'needs' ? ' on' : ''}`;
640
- needsBtn.innerHTML = `Needs you${state.pending.size ? `<span class="badge">${state.pending.size}</span>` : ''}`;
1120
+ const n = state.pending.size;
1121
+ needsBtn.className = `needsbtn${n ? ' has' : ''}${state.screen === 'needs' ? ' on' : ''}`;
1122
+ needsBtn.setAttribute('aria-label', n ? `Needs you: ${n} waiting` : 'Needs you');
1123
+ needsBtn.innerHTML = `${ICON.bell}<span class="nlbl">Needs you</span>${n ? `<span class="badge">${esc(String(n))}</span>` : ''}`;
641
1124
  }
1125
+ const title = document.getElementById('htitle');
1126
+ if (title) title.textContent = 'Picasso';
1127
+ paintSheet();
642
1128
  paintList();
643
1129
  const tv = document.getElementById('threadview');
644
1130
  const nv = document.getElementById('needsview');
@@ -650,6 +1136,18 @@ function paint() {
650
1136
  if (state.screen === 'needs') paintNeeds();
651
1137
  }
652
1138
 
1139
+ function paintSheet() {
1140
+ const dev = document.getElementById('devline');
1141
+ if (!dev || !state.cred) return;
1142
+ dev.textContent = state.cred.device.name || 'This device';
1143
+ const conn = document.getElementById('connline');
1144
+ if (conn) conn.textContent = connLine();
1145
+ const perms = document.getElementById('perms');
1146
+ if (perms) {
1147
+ perms.innerHTML = SCOPES.map((s) => `<li class="${can(s) ? 'yes' : 'no'}" data-scope="${esc(s)}"><span class="pm" aria-hidden="true"></span>${esc(SCOPE_LABELS[s])}<span class="sr">${can(s) ? ' (allowed)' : ' (not allowed)'}</span></li>`).join('');
1148
+ }
1149
+ }
1150
+
653
1151
  function sortedRows() {
654
1152
  return [...state.rows.values()].sort((a, b) => (b.lastUserActivityAt || b.updatedAt || 0) - (a.lastUserActivityAt || a.updatedAt || 0));
655
1153
  }
@@ -663,19 +1161,26 @@ function paintList() {
663
1161
  : `<div class="empty"><div class="big">No threads yet</div>${can('prompt') ? 'Start one on the computer, or here with New.' : 'Threads started on the computer show up here.'}</div>`;
664
1162
  return;
665
1163
  }
1164
+ if (list.querySelector('.empty')) list.replaceChildren();
666
1165
  const needing = new Set([...state.pending.values()].map((p) => p.sessionId));
667
- list.innerHTML = rows.map((r) => {
1166
+ patch(list, rows.map((r) => {
668
1167
  const t = state.threads.get(r.sessionId);
669
1168
  const running = state.running.has(r.sessionId);
670
- const live = running && t && t.liveText ? lastLine(t.liveText) : '';
671
- const mark = needing.has(r.sessionId) ? 'need' : running ? 'run' : 'idle';
672
- const l2 = live || (running ? 'Working…' : r.lastReplyPreview || r.cwd || '');
673
- return `<div class="row${r.sessionId === state.threadId ? ' sel' : ''}" data-act="open" data-id="${esc(r.sessionId)}" role="button" tabindex="0">
1169
+ const needs = needing.has(r.sessionId);
1170
+ const live = running && t && t.liveText ? liveLine(t.liveText) : '';
1171
+ const mark = needs ? 'wait' : running ? 'run' : 'idle';
1172
+ const l2 = live || (running ? 'Working…' : RemoteMarkdown.plain(r.lastReplyPreview || r.firstPrompt || '') || 'No replies yet');
1173
+ const chip = needs ? '<span class="chip wait">Needs you</span>' : running ? '<span class="chip run">Running</span>' : '';
1174
+ const folder = folderName(r.cwd);
1175
+ return { k: r.sessionId, h: `<div class="row${r.sessionId === state.threadId ? ' sel' : ''} is-${mark}" data-act="open" data-id="${esc(r.sessionId)}" role="button" tabindex="0">
674
1176
  <span class="mark ${mark}"></span>
675
- <div class="t"><div class="l1">${esc(r.title || r.cwd || shortId(r.sessionId))}</div><div class="l2${live || running ? ' live' : ''}">${esc(l2)}</div></div>
676
- <span class="when">${esc(fmtWhen(r.updatedAt))}</span>
677
- </div>`;
678
- }).join('');
1177
+ <div class="t">
1178
+ <div class="r1"><span class="l1">${esc(r.title || folder || shortId(r.sessionId))}</span><span class="when">${esc(fmtWhen(r.updatedAt))}</span></div>
1179
+ <div class="l2${live || running ? ' live' : ''}">${esc(l2)}</div>
1180
+ ${chip || folder ? `<div class="r3">${chip}${folder ? `<span class="folder">${esc(folder)}</span>` : ''}</div>` : ''}
1181
+ </div>
1182
+ </div>` };
1183
+ }));
679
1184
  }
680
1185
 
681
1186
  function foldItems(t) {
@@ -683,23 +1188,26 @@ function foldItems(t) {
683
1188
  for (const seq of t.order) {
684
1189
  const event = t.events.get(seq);
685
1190
  const d = event.data || {};
1191
+ const k = `e${seq}`;
686
1192
  switch (event.type) {
687
- case 'turn/start': if (d.turn !== undefined) items.push({ kind: 'note', text: `Turn ${d.turn}` }); break;
1193
+ case 'turn/start': if (d.turn !== undefined) items.push({ k, kind: 'turn', text: `Turn ${d.turn}` }); break;
688
1194
  case 'user/message': {
689
1195
  if (d.role && d.role !== 'user') break;
690
1196
  if (d.source && d.source.kind && d.source.kind !== 'user') break;
691
1197
  const text = blocksText(d.content);
692
- if (text) items.push({ kind: 'user', text });
1198
+ if (text) items.push({ k, kind: 'user', text });
693
1199
  break;
694
1200
  }
695
- case 'assistant/message':
1201
+ case 'assistant/message': {
1202
+ let n = 0;
696
1203
  for (const b of (d.message && d.message.content) || []) {
697
- if (b.type === 'text' && b.text) items.push({ kind: 'bot', text: b.text });
698
- else if ((b.type === 'reasoning' || b.type === 'thinking') && b.text) items.push({ kind: 'think', text: b.text });
1204
+ if (b.type === 'text' && b.text) items.push({ k: `${k}.${n++}`, kind: 'bot', text: b.text });
1205
+ else if ((b.type === 'reasoning' || b.type === 'thinking') && b.text) items.push({ k: `${k}.${n++}`, kind: 'think', text: b.text });
699
1206
  }
700
1207
  break;
1208
+ }
701
1209
  case 'tool/call':
702
- items.push({ kind: 'tool', callId: d.callId || '', name: d.name || 'tool', target: toolTarget(d.arguments), status: 'run' });
1210
+ items.push({ k: `tool:${d.callId || seq}`, kind: 'tool', callId: d.callId || '', name: d.name || 'tool', target: toolTarget(d.arguments), status: 'run' });
703
1211
  break;
704
1212
  case 'tool/result': {
705
1213
  const callId = (d.message && (d.message.toolCallId || (d.message.source && d.message.source.callId))) || d.callId || '';
@@ -707,18 +1215,18 @@ function foldItems(t) {
707
1215
  if (items[i].kind === 'tool' && items[i].callId === callId) {
708
1216
  items[i].status = (d.message && d.message.isError) || d.error ? 'fail' : 'ok';
709
1217
  const full = blocksText(d.message && d.message.content);
710
- if (full) items[i].preview = full.slice(0, 200);
1218
+ if (full) items[i].preview = full.slice(0, 1_200);
711
1219
  break;
712
1220
  }
713
1221
  }
714
1222
  break;
715
1223
  }
716
- case 'approval/asked': items.push({ kind: 'note', text: `Approval asked: ${d.toolName || ''}` }); break;
717
- case 'command/run': items.push({ kind: 'note', text: `/${d.name || 'command'}` }); break;
718
- case 'command/done': if (d.text) items.push({ kind: 'note', text: d.text }); break;
719
- case 'compaction/summary': items.push({ kind: 'note', text: 'Context compacted' }); break;
720
- case 'model/selection': if (d.model) items.push({ kind: 'note', text: `Model: ${d.model}` }); break;
721
- case 'client/note': items.push({ kind: 'note', text: d.text }); break;
1224
+ case 'approval/asked': items.push({ k, kind: 'note', text: `Approval asked: ${d.toolName || ''}` }); break;
1225
+ case 'command/run': items.push({ k, kind: 'note', text: `/${d.name || 'command'}` }); break;
1226
+ case 'command/done': if (d.text) items.push({ k, kind: 'note', text: d.text }); break;
1227
+ case 'compaction/summary': items.push({ k, kind: 'note', text: 'Context compacted' }); break;
1228
+ case 'model/selection': if (d.model) items.push({ k, kind: 'note', text: `Model: ${d.model}` }); break;
1229
+ case 'client/note': items.push({ k, kind: 'note', text: d.text }); break;
722
1230
  default: break;
723
1231
  }
724
1232
  }
@@ -739,48 +1247,86 @@ function toolTarget(args) {
739
1247
  return '';
740
1248
  }
741
1249
 
1250
+ const TOOL_STATUS = { run: 'Running', ok: 'Done', fail: 'Failed' };
1251
+ function toolHtml(i) {
1252
+ const line = `<span class="ti ${i.status}" aria-hidden="true"></span><span class="name">${esc(i.name)}</span><span class="target">${esc(i.target)}</span><span class="st ${i.status}">${TOOL_STATUS[i.status]}</span>`;
1253
+ if (!i.preview) return `<div class="tool" data-call="${esc(i.callId)}"><div class="tline">${line}</div></div>`;
1254
+ return `<details class="tool" data-call="${esc(i.callId)}" data-ok="${esc(i.k)}"><summary class="tline">${line}</summary><pre class="prev">${esc(i.preview)}</pre></details>`;
1255
+ }
1256
+
742
1257
  function itemHtml(i) {
743
1258
  switch (i.kind) {
744
1259
  case 'user': return `<div class="msg user">${esc(i.text)}</div>`;
745
- case 'bot': return `<div class="msg bot">${esc(i.text)}</div>`;
746
- case 'think': return `<div class="msg think">${esc(i.text)}</div>`;
1260
+ case 'bot': return `<div class="msg bot md">${md(i.text)}</div>`;
1261
+ case 'think': return `<details class="think" data-ok="${esc(i.k)}"><summary>Thinking</summary><div class="md">${md(i.text)}</div></details>`;
1262
+ case 'turn': return `<div class="turnsep"><span>${esc(i.text)}</span></div>`;
747
1263
  case 'note': return `<div class="msg note">${esc(i.text)}</div>`;
748
- case 'tool': return `<div class="tool" data-call="${esc(i.callId)}"><span class="name">${esc(i.name)}</span><span class="target">${esc(i.target)}</span><span class="st ${i.status}">${i.status === 'run' ? 'Running' : i.status === 'ok' ? 'Done' : 'Failed'}</span>${i.preview ? `<span class="prev">${esc(i.preview)}</span>` : ''}</div>`;
749
- default: return '';
1264
+ case 'tool': return toolHtml(i);
1265
+ default: return '<div></div>';
750
1266
  }
751
1267
  }
752
1268
 
1269
+ /** Feed parts: consecutive tool calls fold into one collapsible group, so a busy turn reads as one line. */
1270
+ function feedParts(items) {
1271
+ const parts = [];
1272
+ for (let i = 0; i < items.length;) {
1273
+ if (items[i].kind !== 'tool') { parts.push({ k: items[i].k, h: itemHtml(items[i]) }); i += 1; continue; }
1274
+ let j = i;
1275
+ while (j < items.length && items[j].kind === 'tool') j += 1;
1276
+ const run = items.slice(i, j);
1277
+ if (run.length === 1) parts.push({ k: run[0].k, h: toolHtml(run[0]) });
1278
+ else {
1279
+ const key = `g:${run[0].k}`;
1280
+ const active = run.filter((r) => r.status === 'run');
1281
+ const failed = run.filter((r) => r.status === 'fail').length;
1282
+ const status = active.length ? 'run' : failed ? 'fail' : 'ok';
1283
+ const label = active.length ? `Running ${active[active.length - 1].name}` : `${run.length} tool calls`;
1284
+ const meta = failed ? `${failed} failed` : active.length ? `${run.length - active.length} of ${run.length} done` : '';
1285
+ parts.push({ k: key, h: `<details class="steps" data-ok="${esc(key)}"><summary class="tline"><span class="ti ${status}" aria-hidden="true"></span><span class="name">${esc(label)}</span><span class="target">${esc(run.map((r) => r.name).join(', '))}</span>${meta ? `<span class="smeta ${status}">${esc(meta)}</span>` : ''}</summary><div class="steplist">${run.map(toolHtml).join('')}</div></details>` });
1286
+ }
1287
+ i = j;
1288
+ }
1289
+ return parts;
1290
+ }
1291
+
753
1292
  function paintThread() {
754
1293
  const id = state.threadId;
755
1294
  const row = id ? state.rows.get(id) : undefined;
756
- document.getElementById('ttitle').textContent = id ? (row && (row.title || row.cwd)) || shortId(id) : 'New thread';
1295
+ document.getElementById('ttitle').textContent = id ? (row && (row.title || folderName(row.cwd))) || shortId(id) : 'New thread';
757
1296
  document.getElementById('tsub').textContent = id ? (row && row.cwd) || '' : 'Your first message starts it';
758
1297
  const running = Boolean(id) && state.running.has(id);
759
1298
  document.getElementById('stopbtn').hidden = !(running && can('stop'));
760
1299
  const feed = document.getElementById('feed');
761
1300
  if (!id) { feed.innerHTML = '<div class="empty">Write the first message below.</div>'; return; }
762
1301
  const t = thread(id);
763
- const nearBottom = window.innerHeight + window.scrollY >= document.body.scrollHeight - 80;
764
- let html = t.hasMore ? '<button class="btn quiet" data-act="earlier">Show earlier</button>' : '';
765
- html += foldItems(t).map(itemHtml).join('');
766
- if (t.liveThink) html += `<div class="msg think live" id="livethink">${esc(t.liveThink)}</div>`;
767
- if (t.liveText) html += `<div class="msg bot live" id="livetext">${esc(t.liveText)}</div>`;
768
- html += [...state.pending.values()].filter((p) => p.sessionId === id).map(needHtml).join('');
769
- if (running && !t.liveText) html += '<div class="msg working">Working…</div>';
770
- feed.innerHTML = html || (t.loading || !t.loaded ? '<div class="empty">Loading…</div>' : '<div class="empty">Nothing yet.</div>');
771
- if (nearBottom) window.scrollTo(0, document.body.scrollHeight);
1302
+ const stick = state.stick;
1303
+ const parts = [];
1304
+ if (t.hasMore) parts.push({ k: 'earlier', h: '<button class="btn quiet earlier" data-act="earlier">Show earlier</button>' });
1305
+ parts.push(...feedParts(foldItems(t)));
1306
+ if (t.liveThink) parts.push({ k: 'livethink', h: `<details class="think live" id="livethink" data-ok="livethink"><summary>Thinking…</summary><div class="md">${md(t.liveThink)}</div></details>` });
1307
+ if (t.liveText) parts.push({ k: 'livetext', h: `<div class="msg bot md live" id="livetext">${md(t.liveText)}</div>` });
1308
+ for (const p of state.pending.values()) if (p.sessionId === id) parts.push({ k: `need:${p.eventId}`, h: needHtml(p) });
1309
+ if (running && !t.liveText) parts.push({ k: 'working', h: '<div class="msg working"><span class="dots" aria-hidden="true"><i></i><i></i><i></i></span>Working…</div>' });
1310
+ if (!parts.length) {
1311
+ feed.innerHTML = t.loading || !t.loaded ? '<div class="empty">Loading…</div>' : '<div class="empty">Nothing yet.</div>';
1312
+ return;
1313
+ }
1314
+ if (feed.querySelector(':scope > .empty')) feed.replaceChildren();
1315
+ patch(feed, parts);
1316
+ if (stick) scrollFeed(false);
1317
+ else document.getElementById('jump').hidden = false;
772
1318
  }
773
1319
 
774
1320
  function paintNeeds() {
775
1321
  const box = document.getElementById('needs');
776
1322
  const items = [...state.pending.values()];
777
- document.getElementById('needsub').textContent = `${items.length} waiting`;
1323
+ document.getElementById('needsub').textContent = items.length ? `${items.length} waiting` : 'All clear';
778
1324
  box.innerHTML = items.length ? items.map(needHtml).join('') : '<div class="empty"><div class="big">Nothing needs you</div>Approvals and questions land here.</div>';
779
1325
  }
780
1326
 
781
1327
  function needHtml(p) {
782
1328
  const row = state.rows.get(p.sessionId);
783
- const where = `<div class="fine">${esc(row ? row.title || row.cwd || shortId(p.sessionId) : shortId(p.sessionId))}</div>`;
1329
+ const where = `<div class="fine where">${esc(row ? row.title || folderName(row.cwd) || shortId(p.sessionId) : shortId(p.sessionId))}</div>`;
784
1330
  const readOnly = can('approve') ? '' : '<div class="fine">This device can only watch. Answer on the computer.</div>';
785
1331
  if (p.kind === 'question') {
786
1332
  return `<div class="need" data-ev="${esc(p.eventId)}">
@@ -791,10 +1337,10 @@ function needHtml(p) {
791
1337
  <div class="qt">${esc(q.question)}</div>
792
1338
  ${(q.options || []).map((o) => `
793
1339
  <label class="opt"><input type="${q.multiSelect ? 'checkbox' : 'radio'}" name="q-${esc(p.eventId)}-${qi}" value="${esc(o.label)}"${can('approve') ? '' : ' disabled'}>
794
- <span>${esc(o.label)}${o.description ? `<div class="d">${esc(o.description)}</div>` : ''}</span></label>`).join('')}
795
- ${can('approve') ? '<input class="custom field-sm" placeholder="Or your own answer">' : ''}
1340
+ <span>${esc(o.label)}${o.description ? `<span class="d">${esc(o.description)}</span>` : ''}</span></label>`).join('')}
1341
+ ${can('approve') ? '<input class="custom field-sm" placeholder="Or your own answer" aria-label="Your own answer">' : ''}
796
1342
  </div>`).join('')}
797
- ${can('approve') ? `<div class="acts"><button class="btn acc" data-act="answer">Answer</button><button class="btn quiet" data-act="decline">Skip</button></div>` : readOnly}
1343
+ ${can('approve') ? '<div class="acts"><button class="btn acc" data-act="answer">Answer</button><button class="btn quiet" data-act="decline">Skip</button></div>' : readOnly}
798
1344
  ${where}
799
1345
  </div>`;
800
1346
  }
@@ -824,6 +1370,7 @@ function boot() {
824
1370
  shell();
825
1371
  setScreen('threads');
826
1372
  setConn('connecting');
1373
+ fitViewport();
827
1374
  state.lastEventAt = Date.now();
828
1375
  openStream();
829
1376
  }