From af4414f7eeae3d20a5341733feccfee800ec0c27 Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 20:58:14 -0600 Subject: [PATCH 1/7] feat(recorder): add browser note composer script Page-injectable composer opened with Alt+right-click. Point adds element chips, Screenshot and Snapshot add capture chips, and the draft is sent as a note or a bug through the __terrificCompose binding. Built without innerHTML or inline styles so it works on CSP and Trusted Types pages. Not wired into the recorder yet. Co-Authored-By: Claude Opus 5.5 --- src/recorder/composer-script.test.ts | 21 + src/recorder/composer-script.ts | 783 +++++++++++++++++++++++++++ 2 files changed, 804 insertions(+) create mode 100644 src/recorder/composer-script.test.ts create mode 100644 src/recorder/composer-script.ts diff --git a/src/recorder/composer-script.test.ts b/src/recorder/composer-script.test.ts new file mode 100644 index 0000000..5b48998 --- /dev/null +++ b/src/recorder/composer-script.test.ts @@ -0,0 +1,21 @@ +import { equal, match } from 'node:assert/strict'; +import { test } from 'node:test'; +import { COMPOSER_BINDING, composerScript, composerScriptSource } from './composer-script.ts'; + +test('composerScript serializes as JavaScript suitable for injection', () => { + const source = composerScript.toString(); + equal(source.includes(': string'), false); + equal(source.includes(': void'), false); + const injected = composerScriptSource(COMPOSER_BINDING); + match(injected, /^\(function composerScript\(bindingName\s*\)/); + match(injected, /\("__terrificCompose"\)$/); + for (const forbidden of [ + 'innerHTML', + 'outerHTML', + 'insertAdjacentHTML', + 'fonts.googleapis', + 'style="', + ]) { + equal(injected.includes(forbidden), false, `serialized source contains ${forbidden}`); + } +}); diff --git a/src/recorder/composer-script.ts b/src/recorder/composer-script.ts new file mode 100644 index 0000000..2709450 --- /dev/null +++ b/src/recorder/composer-script.ts @@ -0,0 +1,783 @@ +/// + +// This function is serialized and evaluated in the page; keep all helpers local. +export const COMPOSER_BINDING = '__terrificCompose'; +export const composerScript: (bindingName: string) => void = function composerScript(bindingName) { + if (window !== window.top) return; + const w = window as unknown as Record; + if (w.__terrificComposer) return; + w.__terrificComposer = true; + + function h(tag: string, attrs: Record = {}, children: (Node | string)[] = []) { + const el = document.createElement(tag); + for (const [name, value] of Object.entries(attrs)) el.setAttribute(name, value); + el.append(...children); + return el; + } + function svg(paths: string[], size = 14) { + const el = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + for (const [key, value] of Object.entries({ + width: `${size}`, + height: `${size}`, + viewBox: '0 0 24 24', + fill: 'none', + stroke: 'currentColor', + 'stroke-width': '2', + 'stroke-linecap': 'round', + 'stroke-linejoin': 'round', + 'aria-hidden': 'true', + })) + el.setAttribute(key, value); + for (const d of paths) { + const path = document.createElementNS('http://www.w3.org/2000/svg', 'path'); + path.setAttribute('d', d); + el.append(path); + } + return el; + } + const icons = { + msg: ['M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z'], + bug: [ + 'm8 2 1.88 1.88M14.12 3.88 16 2M9 7.13v-1a3 3 0 1 1 6 0v1', + 'M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6M12 20v-9M6.53 9C4.6 8.8 3 7.1 3 5M6 13H2M3 21c0-2.1 1.7-3.9 3.8-4M20.97 5c0 2.1-1.6 3.8-3.5 4M22 13h-4M17.2 17c2.1.1 3.8 1.9 3.8 4', + ], + cam: [ + 'M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z', + 'M15 13a3 3 0 1 1-6 0 3 3 0 0 1 6 0z', + ], + scan: [ + 'M3 7V5a2 2 0 0 1 2-2h2M17 3h2a2 2 0 0 1 2 2v2M21 17v2a2 2 0 0 1-2 2h-2M7 21H5a2 2 0 0 1-2-2v-2M7 12h10', + ], + ptr: [ + 'M4.04 4.69a.5.5 0 0 1 .65-.65l16 6.5a.5.5 0 0 1-.06.95l-6.12 1.58a2 2 0 0 0-1.44 1.44l-1.58 6.12a.5.5 0 0 1-.95.07z', + ], + x: ['M18 6 6 18M6 6l12 12'], + }; + const css = ` +:host{all:initial} +*{box-sizing:border-box} +[hidden]{display:none!important} +.layer{position:fixed;inset:0;pointer-events:none;z-index:2147483646;font:500 13px/1.4 Inter,system-ui,"Segoe UI",sans-serif;color:#e4e4e7;-webkit-font-smoothing:antialiased} +.layer.capturing{visibility:hidden} +button{font:inherit;cursor:pointer} +button:focus-visible{outline:2px solid rgba(255,255,255,.45);outline-offset:1px} +button:disabled{cursor:default;opacity:.4} +.panel{position:fixed;pointer-events:auto;width:366px;max-width:calc(100vw - 16px);background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,.5);overflow:hidden} +.hd{display:flex;align-items:center;gap:8px;height:38px;padding:0 6px 0 12px;background:rgba(24,24,27,.8);border-bottom:1px solid rgba(255,255,255,.05);cursor:grab;color:#52525b;user-select:none;touch-action:none} +.hd.dragging{cursor:grabbing} +.hd h2{margin:0;font:700 11px Inter,system-ui,sans-serif;letter-spacing:.06em;text-transform:uppercase;color:#fff} +.ib{margin-left:auto;width:28px;height:28px;display:grid;place-items:center;border:0;border-radius:8px;background:transparent;color:#71717a} +.ib:hover{color:#fff;background:rgba(255,255,255,.05)} +.edwrap{position:relative;background:#09090b} +.edwrap:focus-within{box-shadow:inset 0 0 0 1px rgba(255,255,255,.12)} +.ed{min-height:96px;max-height:240px;overflow:auto;padding:12px 14px;font:400 14px/1.85 Inter,system-ui,sans-serif;color:#f4f4f5;outline:none;white-space:pre-wrap;word-break:break-word;caret-color:#fff} +.ed.empty::before{content:attr(data-placeholder);color:#52525b;position:absolute;pointer-events:none} +.ch{display:inline-flex;align-items:center;gap:4px;height:21px;padding:0 6px;margin:0 1px;vertical-align:1px;border-radius:6px;font:500 12px/1 "JetBrains Mono",Consolas,monospace;white-space:nowrap;user-select:all;cursor:default} +.ch.el{background:rgba(99,102,241,.15);border:1px solid rgba(99,102,241,.1);color:#a5b4fc} +.ch.cap{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#e4e4e7;font-family:Inter,system-ui,sans-serif} +.ch.cap svg{color:#22d3ee} +.ch:hover{filter:brightness(1.25)} +.ch .rm{display:none;width:14px;height:14px;margin:0 -2px 0 1px;border:0;padding:0;border-radius:3px;background:transparent;color:inherit;place-items:center} +.ch:hover .rm{display:inline-grid} +.ch .rm:hover{background:rgba(255,255,255,.12)} +.tools{display:flex;align-items:center;gap:2px;padding:6px 8px;background:#18181b;border-top:1px solid rgba(255,255,255,.05)} +.tl{display:inline-flex;align-items:center;gap:6px;height:28px;padding:0 8px;border:0;border-radius:8px;background:transparent;color:#a1a1aa;font-size:12px;font-weight:500} +.tl svg{color:#71717a} +.tl:hover:not(:disabled){color:#fff;background:rgba(255,255,255,.05)} +.tl:hover:not(:disabled) svg{color:#fff} +.tl[aria-pressed=true]{background:rgba(99,102,241,.15);color:#a5b4fc} +.tl[aria-pressed=true] svg{color:#a5b4fc} +.ft{display:flex;align-items:center;gap:6px;padding:8px;border-top:1px solid rgba(255,255,255,.05);background:#18181b;min-height:47px} +.idle{display:contents} +.hint{font:400 11px "JetBrains Mono",Consolas,monospace;color:#71717a;padding:0 6px;display:flex;align-items:center;gap:4px} +kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px solid rgba(255,255,255,.1);border-radius:4px;padding:1px 4px} +.bn{height:30px;padding:0 10px;border-radius:8px;display:inline-flex;align-items:center;gap:6px;font-size:13px;font-weight:500;border:1px solid transparent} +.bb{margin-left:auto;background:rgba(239,68,68,.1);color:#f87171;border-color:rgba(239,68,68,.2)} +.bb:hover:not(:disabled){background:rgba(239,68,68,.2)} +.bw{background:#fff;color:#000} +.bw:hover:not(:disabled){background:#e4e4e7} +.err{margin:0;padding:8px 14px;font-size:12px;color:#fca5a5;background:rgba(239,68,68,.08);border-top:1px solid rgba(239,68,68,.15)} +.hl,.ref{position:fixed;pointer-events:none;border-radius:4px} +.hl{border:2px solid #a5b4fc;background:rgba(165,180,252,.14)} +.ref{border:2px dashed #a5b4fc} +.tg{position:absolute;left:-2px;bottom:100%;background:#a5b4fc;color:#09090b;font:500 11px/18px "JetBrains Mono",Consolas,monospace;padding:0 6px;border-radius:4px 4px 0 0;white-space:nowrap} +.tg.inside{bottom:auto;top:0;border-radius:0 0 4px 0} +.pop{position:fixed;width:224px;padding:6px;background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:10px;box-shadow:0 12px 30px rgba(0,0,0,.45)} +.pop .im{position:relative;max-height:160px;border-radius:6px;overflow:hidden;background:#fff} +.pop img{display:block;width:100%;height:auto} +.pop .meta{display:flex;justify-content:space-between;gap:8px;margin:6px 2px 0;font:400 11px Inter,system-ui,sans-serif;color:#a1a1aa} +.pop .meta b{color:#e4e4e7;font-weight:500} +.pop .sn{padding:4px 4px 2px;font:400 12px/1.5 Inter,system-ui,sans-serif;color:#a1a1aa} +.pop .sn b{display:block;color:#e4e4e7;font-weight:500;margin-bottom:2px} +.pop .excerpt{margin-top:4px;color:#71717a} +.toast{position:fixed;right:20px;bottom:20px;pointer-events:auto;display:flex;align-items:center;gap:8px;padding:10px 14px;background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:12px;box-shadow:0 12px 30px rgba(0,0,0,.4);color:#e4e4e7} +.toast svg{color:#a5b4fc} +.toast.bug svg{color:#f87171} +@media (max-width:420px){.toast{right:12px;left:12px;bottom:12px}} +`; + const host = document.createElement('terrific-composer'); + // Init scripts can run before exists; the Alt+right-click handler attaches the host on demand. + if (document.documentElement) document.documentElement.append(host); + const root = host.attachShadow({ mode: 'open' }); + if ( + 'adoptedStyleSheets' in root && + typeof CSSStyleSheet !== 'undefined' && + 'replaceSync' in CSSStyleSheet.prototype + ) { + const sheet = new CSSStyleSheet(); + sheet.replaceSync(css); + root.adoptedStyleSheets = [sheet]; + } else { + const style = document.createElement('style'); + style.textContent = css; + root.append(style); + } + const button = ( + cls: string, + label: string, + icon: string[], + attrs: Record = {}, + ) => { + const text = h('span', {}, [label]); + const el = h('button', { class: cls, type: 'button', ...attrs }, [ + svg(icon), + text, + ]) as HTMLButtonElement; + return { el, text }; + }; + const layer = h('div', { class: 'layer' }); + const ref = h('div', { class: 'ref', hidden: '' }); + const tag = h('span', { class: 'tg' }); + const hl = h('div', { class: 'hl', hidden: '' }, [tag]); + const panel = h('section', { + class: 'panel', + role: 'dialog', + 'aria-modal': 'false', + 'aria-labelledby': 'tc-title', + hidden: '', + }); + const grip = document.createElementNS('http://www.w3.org/2000/svg', 'svg'); + for (const [key, value] of Object.entries({ + width: '10', + height: '16', + viewBox: '0 0 10 16', + fill: 'currentColor', + 'aria-hidden': 'true', + })) + grip.setAttribute(key, value); + for (const x of [2, 8]) + for (const y of [3, 8, 13]) { + const circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle'); + circle.setAttribute('cx', `${x}`); + circle.setAttribute('cy', `${y}`); + circle.setAttribute('r', '1.4'); + grip.append(circle); + } + const closeBtn = h( + 'button', + { + class: 'ib close', + type: 'button', + 'aria-label': 'Close', + title: 'Close (Esc). The draft is kept.', + }, + [svg(icons.x)], + ); + const hd = h('div', { class: 'hd' }, [grip, h('h2', { id: 'tc-title' }, ['New note']), closeBtn]); + const ed = h('div', { + class: 'ed empty', + contenteditable: 'true', + role: 'textbox', + 'aria-multiline': 'true', + 'aria-labelledby': 'tc-title', + 'data-placeholder': 'Describe what happened', + spellcheck: 'true', + }); + const point = button('tl', 'Point', icons.ptr, { 'aria-pressed': 'false' }); + const shot = button('tl', 'Screenshot', icons.cam); + const snap = button('tl', 'Snapshot', icons.scan); + const err = h('p', { class: 'err', role: 'alert', hidden: '' }); + const bug = button('bn bb', 'Bug', icons.bug, { title: 'Save as bug (Ctrl+Shift+Enter)' }); + const note = button('bn bw', 'Note', icons.msg, { title: 'Save as note (Ctrl+Enter)' }); + const idle = h('div', { class: 'idle' }, [ + h('span', { class: 'hint' }, [h('kbd', {}, ['Ctrl']), h('kbd', {}, ['↵']), ' note']), + bug.el, + note.el, + ]); + const pointingHint = h('span', { class: 'hint', hidden: '' }, [ + 'click to add · ↑↓ level · enter · esc', + ]); + panel.append( + hd, + h('div', { class: 'edwrap' }, [ed]), + h('div', { class: 'tools' }, [point.el, shot.el, snap.el]), + err, + h('div', { class: 'ft' }, [idle, pointingHint]), + ); + const pop = h('div', { class: 'pop', hidden: '' }); + const toast = h('div', { class: 'toast', role: 'status', 'aria-live': 'polite', hidden: '' }); + layer.append(ref, hl, panel, pop, toast); + root.append(layer); + type Chip = + | { kind: 'element'; el: Element; selector: string; name: string } + | { + kind: 'screenshot'; + label: string; + file: string; + width: number; + height: number; + preview: string | null; + } + | { + kind: 'snapshot'; + label: string; + id: string | null; + title: string; + wordCount: number; + excerpt: string; + }; + const chipData = new WeakMap(); + const counters = { screenshot: 0, snapshot: 0 }; + let savedRange: Range | null = null; + let busy = false; + let moved = false; + let toastTimer: ReturnType | undefined; + const selection = () => + 'getSelection' in root && typeof root.getSelection === 'function' + ? (root.getSelection as () => Selection | null)() + : document.getSelection(); + const clamp = (v: number, lo: number, hi: number) => Math.max(lo, Math.min(hi, v)); + const isOurs = (e: Event) => e.composedPath().includes(host); + const usable = (el: Element | null): el is Element => + !!el && el !== document.documentElement && el !== document.body && el !== host; + function selectorFor(el: Element) { + const parts: string[] = []; + for ( + let n: Element | null = el; + n && n !== document.body && parts.length < 4; + n = n.parentElement + ) { + if (n.id) { + parts.unshift( + `${n.localName}#${typeof window.CSS === 'undefined' ? n.id : CSS.escape(n.id)}`, + ); + break; + } + let part = n.localName; + const siblings = n.parentElement + ? Array.from(n.parentElement.children).filter((c) => c.localName === n?.localName) + : []; + if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(n) + 1})`; + parts.unshift(part); + } + return parts.join(' > '); + } + function accessibleName(el: Element) { + const labelled = 'labels' in el ? (el as HTMLInputElement).labels?.[0] : null; + const heading = el.querySelector('h1,h2,h3,h4,h5,h6,legend,caption'); + const visible = (node: Element | null) => + // biome-ignore lint/performance/useDomNodeTextContent: visible text matches the mock's accessible names. + node instanceof HTMLElement ? node.innerText : node?.textContent || ''; + const leaf = + el.childElementCount === 0 && !/^(input|textarea|select)$/.test(el.localName) + ? visible(el) + : ''; + return ( + el.getAttribute('aria-label') || + visible(labelled || null) || + visible(heading) || + leaf || + '' + ) + .replace(/\s+/g, ' ') + .trim() + .slice(0, 40); + } + function hasContent() { + return !!ed.textContent?.trim() || !!ed.querySelector('.ch'); + } + function update() { + if (!hasContent()) ed.replaceChildren(); + ed.classList.toggle('empty', !hasContent()); + note.el.disabled = busy || !hasContent(); + bug.el.disabled = busy; + for (const b of [point.el, shot.el, snap.el]) b.disabled = busy; + } + function endRange() { + const r = document.createRange(); + r.selectNodeContents(ed); + r.collapse(false); + return r; + } + function placeCaret(r: Range) { + const s = selection(); + if (!s) return; + s.removeAllRanges(); + s.addRange(r); + savedRange = r.cloneRange(); + } + function rangeInEditor() { + return savedRange && ed.contains(savedRange.startContainer) + ? savedRange.cloneRange() + : endRange(); + } + function needsLeadingSpace(r: Range) { + const c = r.startContainer, + o = r.startOffset; + if (c.nodeType === Node.TEXT_NODE) return o > 0 && !/\s/.test((c as Text).data.charAt(o - 1)); + const prev = c.childNodes[o - 1]; + if (!prev) return false; + return prev.nodeType === Node.TEXT_NODE + ? !/\s$/.test((prev as Text).data) + : prev.nodeName !== 'BR'; + } + function insertChip(chip: HTMLElement) { + ed.focus({ preventScroll: true }); + const r = rangeInEditor(); + r.deleteContents(); + const after = document.createTextNode(' '), + frag = document.createDocumentFragment(); + if (needsLeadingSpace(r)) frag.append(' '); + frag.append(chip, after); + r.insertNode(frag); + const caret = document.createRange(); + caret.setStartAfter(after); + caret.collapse(true); + placeCaret(caret); + update(); + } + function makeChip(data: Chip, label: string, icon?: string[]) { + const chip = h('span', { + class: `ch ${data.kind === 'element' ? 'el' : 'cap'}`, + contenteditable: 'false', + }); + if (icon) chip.append(svg(icon, 12)); + chip.append( + h('span', {}, [label]), + h('button', { class: 'rm', type: 'button', tabindex: '-1', 'aria-label': 'Remove' }, [ + svg(icons.x, 10), + ]), + ); + chipData.set(chip, data); + return chip; + } + function addElement(el: Element | null) { + if (!usable(el)) return; + const selector = selectorFor(el); + const chip = makeChip( + { kind: 'element', el, selector, name: accessibleName(el) }, + `<${el.localName}>`, + ); + chip.title = selector; + insertChip(chip); + } + document.addEventListener('selectionchange', () => { + const s = selection(); + if (s?.rangeCount && ed.contains(s.getRangeAt(0).startContainer)) + savedRange = s.getRangeAt(0).cloneRange(); + }); + ed.addEventListener('input', () => { + hideError(); + update(); + }); + ed.addEventListener('paste', (e) => { + e.preventDefault(); + document.execCommand('insertText', false, e.clipboardData?.getData('text/plain') || ''); + }); + ed.addEventListener('keydown', (e) => { + if (e.key === 'Enter' && !e.ctrlKey && !e.metaKey && !e.shiftKey) { + e.preventDefault(); + document.execCommand('insertLineBreak'); + } + }); + ed.addEventListener('click', (e) => { + const rm = (e.target as Element).closest('.rm'); + if (!rm) return; + rm.closest('.ch')?.remove(); + hidePreview(); + update(); + ed.focus(); + }); + let pointing = false, + chain: Element[] = [], + level = 0; + const cursorStyle = document.createElement('style'); + cursorStyle.textContent = + 'html.terrific-pointing, html.terrific-pointing *{cursor:crosshair!important}'; + function drawHighlight() { + const el = chain[level]; + if (!el) { + hl.hidden = true; + return; + } + const r = el.getBoundingClientRect(); + Object.assign(hl.style, { + left: `${r.left - 2}px`, + top: `${r.top - 2}px`, + width: `${r.width + 4}px`, + height: `${r.height + 4}px`, + }); + tag.textContent = + el.localName + + (el.id + ? `#${el.id}` + : typeof el.className === 'string' && el.className.trim() + ? `.${el.className.trim().split(/\s+/)[0]}` + : ''); + tag.classList.toggle('inside', r.top < 22); + hl.hidden = false; + } + function startPoint() { + if (pointing) return; + pointing = true; + point.el.setAttribute('aria-pressed', 'true'); + idle.hidden = true; + pointingHint.hidden = false; + (document.head || document.documentElement).append(cursorStyle); + document.documentElement.classList.add('terrific-pointing'); + for (const [type, fn] of pointerHandlers) window.addEventListener(type, fn, true); + } + function stopPoint() { + if (!pointing) return; + pointing = false; + point.el.setAttribute('aria-pressed', 'false'); + idle.hidden = false; + pointingHint.hidden = true; + hl.hidden = true; + chain = []; + level = 0; + document.documentElement.classList.remove('terrific-pointing'); + cursorStyle.remove(); + for (const [type, fn] of pointerHandlers) window.removeEventListener(type, fn, true); + } + const block = (e: Event) => { + if (isOurs(e)) return; + e.preventDefault(); + e.stopImmediatePropagation(); + }; + function firstTarget(e: Event): Element | null { + const t = e.composedPath()[0]; + return t instanceof Element ? t : t instanceof Node ? t.parentElement : null; + } + function pick(el: Element | null) { + stopPoint(); + addElement(el); + } + const pointerHandlers: [string, EventListener][] = [ + [ + 'pointermove', + (e) => { + if (isOurs(e)) { + hl.hidden = true; + chain = []; + return; + } + const el = firstTarget(e); + if (chain[0] === el) return; + chain = []; + for (let n = el; usable(n); n = n.parentElement) chain.push(n); + level = 0; + drawHighlight(); + }, + ], + ['pointerdown', block], + ['mousedown', block], + ['mouseup', block], + ['pointerup', block], + [ + 'click', + (e) => { + if (isOurs(e)) return; + e.preventDefault(); + e.stopImmediatePropagation(); + pick(chain[level] || firstTarget(e)); + }, + ], + [ + 'keydown', + (e) => { + const key = (e as KeyboardEvent).key; + if (key === 'Escape') { + e.preventDefault(); + e.stopImmediatePropagation(); + stopPoint(); + ed.focus(); + return; + } + if (!chain.length) return; + if (key === 'ArrowUp' || key === 'ArrowDown') { + e.preventDefault(); + e.stopImmediatePropagation(); + level = clamp(level + (key === 'ArrowUp' ? 1 : -1), 0, chain.length - 1); + drawHighlight(); + } else if (key === 'Enter') { + e.preventDefault(); + e.stopImmediatePropagation(); + pick(chain[level] || null); + } + }, + ], + ['scroll', () => drawHighlight()], + ]; + point.el.addEventListener('click', () => { + if (pointing) { + stopPoint(); + ed.focus(); + } else startPoint(); + }); + function keepInView() { + if (panel.hidden) return; + const r = panel.getBoundingClientRect(); + panel.style.left = `${clamp(r.left, 8, Math.max(8, innerWidth - r.width - 8))}px`; + panel.style.top = `${clamp(r.top, 8, Math.max(8, innerHeight - r.height - 8))}px`; + } + window.addEventListener('resize', keepInView); + hd.addEventListener('pointerdown', (e) => { + if (e.button !== 0 || (e.target as Element).closest('button')) return; + const r = panel.getBoundingClientRect(), + dx = e.clientX - r.left, + dy = e.clientY - r.top; + hd.setPointerCapture(e.pointerId); + hd.classList.add('dragging'); + const move = (ev: PointerEvent) => { + panel.style.left = `${clamp(ev.clientX - dx, 8, Math.max(8, innerWidth - r.width - 8))}px`; + panel.style.top = `${clamp(ev.clientY - dy, 8, Math.max(8, innerHeight - r.height - 8))}px`; + }; + const up = () => { + hd.classList.remove('dragging'); + moved = true; + hd.removeEventListener('pointermove', move); + hd.removeEventListener('pointerup', up); + hd.removeEventListener('pointercancel', up); + }; + hd.addEventListener('pointermove', move); + hd.addEventListener('pointerup', up); + hd.addEventListener('pointercancel', up); + }); + function hidePreview() { + ref.hidden = true; + pop.hidden = true; + pop.replaceChildren(); + } + ed.addEventListener('mouseover', (e) => { + const chip = (e.target as Element).closest('.ch'); + if (!chip) return; + const data = chipData.get(chip); + if (!data) return; + if (data.kind === 'element') { + if (!data.el.isConnected) return; + const r = data.el.getBoundingClientRect(); + Object.assign(ref.style, { + left: `${r.left - 3}px`, + top: `${r.top - 3}px`, + width: `${r.width + 6}px`, + height: `${r.height + 6}px`, + }); + ref.hidden = false; + return; + } + pop.replaceChildren(); + if (data.kind === 'screenshot') { + if (data.preview) { + const img = h('img', { src: data.preview, alt: '' }) as HTMLImageElement; + const container = h('div', { class: 'im' }, [img]); + img.addEventListener('error', () => container.remove()); + pop.append(container); + } + pop.append( + h('div', { class: 'meta' }, [ + h('b', {}, [data.label]), + h('span', {}, [`${data.width}×${data.height}`]), + ]), + ); + } else { + pop.append( + h('div', { class: 'sn' }, [ + h('b', {}, [`${data.label} · page scrape`]), + h('span', {}, [`${data.title} · ${data.wordCount} words`]), + h('div', { class: 'excerpt' }, [`${data.excerpt}…`]), + ]), + ); + } + pop.hidden = false; + const cr = chip.getBoundingClientRect(), + pr = pop.getBoundingClientRect(); + pop.style.left = `${clamp(cr.left + cr.width / 2 - pr.width / 2, 8, innerWidth - pr.width - 8)}px`; + pop.style.top = `${cr.top - pr.height - 8 >= 8 ? cr.top - pr.height - 8 : cr.bottom + 8}px`; + }); + ed.addEventListener('mouseout', (e) => { + const chip = (e.target as Element).closest('.ch'); + if (chip && !(e.relatedTarget instanceof Node && chip.contains(e.relatedTarget))) hidePreview(); + }); + async function bridge(op: string, payload?: unknown): Promise { + const fn = w[bindingName]; + if (typeof fn !== 'function') throw new Error('Terrific is not connected to this page.'); + return payload === undefined ? fn(op) : fn(op, payload); + } + const frame = () => + new Promise((resolve) => + requestAnimationFrame(() => requestAnimationFrame(() => resolve())), + ); + async function capture(kind: 'screenshot' | 'snapshot') { + if (busy) return; + stopPoint(); + hideError(); + hidePreview(); + const btn = kind === 'screenshot' ? shot : snap, + label = btn.text.textContent; + busy = true; + update(); + btn.text.textContent = kind === 'screenshot' ? 'Capturing…' : 'Reading page…'; + try { + let chip: HTMLElement; + if (kind === 'screenshot') { + layer.classList.add('capturing'); + let res: { file: string; width: number; height: number; preview: string | null }; + try { + await frame(); + res = await bridge('screenshot'); + } finally { + layer.classList.remove('capturing'); + } + const name = `Screenshot ${++counters.screenshot}`; + chip = makeChip({ kind: 'screenshot', label: name, ...res }, name, icons.cam); + } else { + const res = await bridge<{ + id: string | null; + title: string; + wordCount: number; + excerpt: string; + }>('snapshot'); + const name = `Snapshot ${++counters.snapshot}`; + chip = makeChip({ kind: 'snapshot', label: name, ...res }, name, icons.scan); + } + busy = false; + insertChip(chip); + } catch (error) { + showError( + `${kind === 'screenshot' ? 'Screenshot' : 'Snapshot'} failed: ${error instanceof Error ? error.message : String(error)}`, + ); + } finally { + busy = false; + btn.text.textContent = label; + update(); + } + } + shot.el.addEventListener('click', () => { + void capture('screenshot'); + }); + snap.el.addEventListener('click', () => { + void capture('snapshot'); + }); + function serialize(node: Node = ed): string { + let out = ''; + for (const n of node.childNodes) { + if (n.nodeType === Node.TEXT_NODE) out += (n as Text).data; + else if (n.nodeName === 'BR') out += '\n'; + else if (n instanceof Element && n.classList.contains('ch')) { + const d = chipData.get(n); + if (!d) continue; + if (d.kind === 'element') out += `[element ${d.selector}${d.name ? ` "${d.name}"` : ''}]`; + else if (d.kind === 'screenshot') out += `[screenshot ${d.file}]`; + else out += d.id ? `[snapshot ${d.id}]` : '[snapshot]'; + } else out += (n.nodeName === 'DIV' && out && !out.endsWith('\n') ? '\n' : '') + serialize(n); + } + return out; + } + function showError(msg: string) { + err.textContent = msg; + err.hidden = false; + } + function hideError() { + err.hidden = true; + } + function close() { + stopPoint(); + hidePreview(); + hideError(); + panel.hidden = true; + } + function showToast(kind: 'note' | 'bug') { + toast.className = `toast${kind === 'bug' ? ' bug' : ''}`; + toast.replaceChildren( + svg(kind === 'bug' ? icons.bug : icons.msg), + h('span', {}, [`${kind === 'bug' ? 'Bug' : 'Note'} saved to the session`]), + ); + toast.hidden = false; + clearTimeout(toastTimer); + toastTimer = setTimeout(() => { + toast.hidden = true; + }, 2600); + } + async function send(kind: 'note' | 'bug') { + if (busy || (kind === 'note' && !hasContent())) return; + stopPoint(); + hideError(); + hidePreview(); + const btn = kind === 'bug' ? bug : note; + const text = serialize() + .replace(/[ \t]+\n/g, '\n') + .replace(/\s+$/, '') + .replace(/^\s+/, ''); + busy = true; + update(); + btn.text.textContent = 'Saving…'; + try { + await bridge('submit', { kind, text: text || null }); + ed.replaceChildren(); + savedRange = null; + close(); + showToast(kind); + } catch (error) { + showError( + `Not saved: ${error instanceof Error ? error.message : String(error)} Your draft is kept.`, + ); + } finally { + busy = false; + btn.text.textContent = kind === 'bug' ? 'Bug' : 'Note'; + update(); + } + } + bug.el.addEventListener('click', () => { + void send('bug'); + }); + note.el.addEventListener('click', () => { + void send('note'); + }); + closeBtn.addEventListener('click', close); + panel.addEventListener('keydown', (e) => { + if ((e.ctrlKey || e.metaKey) && e.key === 'Enter') { + e.preventDefault(); + void send(e.shiftKey ? 'bug' : 'note'); + } else if (e.key === 'Escape' && !pointing) { + e.preventDefault(); + close(); + } + }); + update(); + window.addEventListener( + 'contextmenu', + (e) => { + if (!e.altKey || isOurs(e)) return; + e.preventDefault(); + e.stopImmediatePropagation(); + if (!host.isConnected) document.documentElement.append(host); + if (pointing) stopPoint(); + const wasOpen = !panel.hidden; + panel.hidden = false; + if (!wasOpen && !moved) { + const r = panel.getBoundingClientRect(); + panel.style.left = `${clamp(e.clientX + 12, 8, Math.max(8, innerWidth - r.width - 8))}px`; + panel.style.top = `${e.clientY + 12 + r.height <= innerHeight - 8 ? e.clientY + 12 : clamp(e.clientY - r.height - 12, 8, Math.max(8, innerHeight - r.height - 8))}px`; + } + keepInView(); + ed.focus({ preventScroll: true }); + placeCaret(rangeInEditor()); + }, + true, + ); +}; + +export function composerScriptSource(bindingName: string): string { + return `(${composerScript.toString()})(${JSON.stringify(bindingName)})`; +} From c3511ea964af1c8f67714b00999108c4d9f958dd Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 21:05:26 -0600 Subject: [PATCH 2/7] feat(recorder): connect the browser composer to live sessions Every recorded browser now gets the composer and a __terrificCompose binding, even when action recording is off. Notes and bugs are stored as tester marks, and the Screenshot and Snapshot tools append real capture events whose ids go back to the page for the chips. The action recorder ignores events from the composer UI. Co-Authored-By: Claude Opus 5.5 --- src/daemon/session-service.ts | 1 + src/recorder/composer-bridge.test.ts | 141 ++++++++++++++++ src/recorder/composer-bridge.ts | 63 +++++++ src/recorder/page-script.ts | 12 ++ src/recorder/recording.ts | 145 +++++++++++++--- test/recorder.test.ts | 244 +++++++++++++++++++++++++++ 6 files changed, 578 insertions(+), 28 deletions(-) create mode 100644 src/recorder/composer-bridge.test.ts create mode 100644 src/recorder/composer-bridge.ts diff --git a/src/daemon/session-service.ts b/src/daemon/session-service.ts index 28fe3eb..08f2d0d 100644 --- a/src/daemon/session-service.ts +++ b/src/daemon/session-service.ts @@ -184,6 +184,7 @@ export function createSessionService(options: { onEvent: (input) => { void appendInput(live, input, stamp); }, + appendEvent: async (input) => ({ id: (await appendInput(live, input, stamp)).id }), }); void live.recording.closed.then((reason) => { if (reason === 'browser-closed') void stop(created.record.id, undefined, true); diff --git a/src/recorder/composer-bridge.test.ts b/src/recorder/composer-bridge.test.ts new file mode 100644 index 0000000..8e40999 --- /dev/null +++ b/src/recorder/composer-bridge.test.ts @@ -0,0 +1,141 @@ +import { deepEqual, equal, rejects } from 'node:assert/strict'; +import { test } from 'node:test'; +import { + type ComposerBridgeDeps, + type ComposerScreenshotResult, + type ComposerSnapshotResult, + type ComposerSubmitResult, + handleComposerRequest, +} from './composer-bridge.ts'; + +function deps(overrides: Partial = {}): ComposerBridgeDeps { + return { + screenshot: async () => ({ + file: 'screenshots/ss_x.png', + width: 800, + height: 600, + preview: null, + }), + snapshot: async () => ({ + id: 'ev_1', + title: 'Page', + wordCount: 3, + excerpt: 'hello world', + }), + submit: async () => ({ id: 'ev_2' }), + ...overrides, + }; +} + +test('handleComposerRequest dispatches screenshot', async () => { + const shot: ComposerScreenshotResult = { + file: 'screenshots/ss_a.png', + width: 10, + height: 20, + preview: 'data:image/png;base64,xx', + }; + const result = await handleComposerRequest( + 'screenshot', + undefined, + deps({ + screenshot: async () => shot, + }), + ); + deepEqual(result, shot); +}); + +test('handleComposerRequest dispatches snapshot', async () => { + const snap: ComposerSnapshotResult = { + id: null, + title: 'T', + wordCount: 0, + excerpt: '', + }; + const result = await handleComposerRequest( + 'snapshot', + undefined, + deps({ + snapshot: async () => snap, + }), + ); + deepEqual(result, snap); +}); + +test('handleComposerRequest submits a note', async () => { + let seen: { kind: string; text: string | null } | null = null; + const result = await handleComposerRequest( + 'submit', + { kind: 'note', text: 'hello' }, + deps({ + submit: async (kind, text) => { + seen = { kind, text }; + return { id: 'ev_note' } satisfies ComposerSubmitResult; + }, + }), + ); + deepEqual(seen, { kind: 'note', text: 'hello' }); + deepEqual(result, { id: 'ev_note' }); +}); + +test('handleComposerRequest requires note text', async () => { + await rejects( + () => handleComposerRequest('submit', { kind: 'note', text: null }, deps()), + (error: unknown) => error instanceof Error && error.message === 'Note text is required.', + ); + await rejects( + () => handleComposerRequest('submit', { kind: 'note', text: ' ' }, deps()), + (error: unknown) => error instanceof Error && error.message === 'Note text is required.', + ); +}); + +test('handleComposerRequest stores blank bug text as null', async () => { + let seen: string | null | undefined; + await handleComposerRequest( + 'submit', + { kind: 'bug', text: ' ' }, + deps({ + submit: async (_kind, text) => { + seen = text; + return { id: null }; + }, + }), + ); + equal(seen, null); + + await handleComposerRequest( + 'submit', + { kind: 'bug', text: null }, + deps({ + submit: async (_kind, text) => { + seen = text; + return { id: null }; + }, + }), + ); + equal(seen, null); +}); + +test('handleComposerRequest rejects text longer than 20000 characters', async () => { + const long = 'x'.repeat(20_001); + await rejects( + () => handleComposerRequest('submit', { kind: 'note', text: long }, deps()), + (error: unknown) => error instanceof Error && error.message === 'Note is too long.', + ); + await rejects( + () => handleComposerRequest('submit', { kind: 'bug', text: long }, deps()), + (error: unknown) => error instanceof Error && error.message === 'Bug is too long.', + ); +}); + +test('handleComposerRequest rejects unknown ops and malformed payloads', async () => { + const message = (error: unknown) => + error instanceof Error && error.message === 'Unsupported composer request.'; + await rejects(() => handleComposerRequest('zoom', undefined, deps()), message); + await rejects(() => handleComposerRequest('submit', null, deps()), message); + await rejects( + () => handleComposerRequest('submit', { kind: 'flag', text: 'x' }, deps()), + message, + ); + await rejects(() => handleComposerRequest('submit', { kind: 'note', text: 1 }, deps()), message); + await rejects(() => handleComposerRequest('submit', { kind: 'bug' }, deps()), message); +}); diff --git a/src/recorder/composer-bridge.ts b/src/recorder/composer-bridge.ts new file mode 100644 index 0000000..f536c4c --- /dev/null +++ b/src/recorder/composer-bridge.ts @@ -0,0 +1,63 @@ +export type ComposerScreenshotResult = { + file: string; + width: number; + height: number; + preview: string | null; +}; + +export type ComposerSnapshotResult = { + id: string | null; + title: string; + wordCount: number; + excerpt: string; +}; + +export type ComposerSubmitResult = { + id: string | null; +}; + +export type ComposerBridgeDeps = { + screenshot: () => Promise; + snapshot: () => Promise; + submit: (kind: 'note' | 'bug', text: string | null) => Promise; +}; + +const MAX_TEXT = 20_000; + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value); +} + +function unsupported(): never { + throw new Error('Unsupported composer request.'); +} + +export async function handleComposerRequest( + op: unknown, + payload: unknown, + deps: ComposerBridgeDeps, +): Promise { + if (op === 'screenshot') return deps.screenshot(); + if (op === 'snapshot') return deps.snapshot(); + if (op !== 'submit') unsupported(); + + if (!isRecord(payload)) unsupported(); + const kind = payload.kind; + const text = payload.text; + if (kind !== 'note' && kind !== 'bug') unsupported(); + if (!(text === null || typeof text === 'string')) unsupported(); + + if (typeof text === 'string' && text.length > MAX_TEXT) { + throw new Error(kind === 'note' ? 'Note is too long.' : 'Bug is too long.'); + } + + if (kind === 'note') { + if (text === null || text.trim() === '') { + throw new Error('Note text is required.'); + } + return deps.submit('note', text); + } + + const stored = text === null || text.trim() === '' ? null : text; + return deps.submit('bug', stored); +} diff --git a/src/recorder/page-script.ts b/src/recorder/page-script.ts index b93a901..c1b0631 100644 --- a/src/recorder/page-script.ts +++ b/src/recorder/page-script.ts @@ -222,9 +222,17 @@ export const pageScript: (bindingName: string) => void = function pageScript(bin return ''; } + function fromComposer(event: Event) { + for (const node of event.composedPath()) { + if (node instanceof Element && node.localName === 'terrific-composer') return true; + } + return false; + } + document.addEventListener( 'click', (event) => { + if (fromComposer(event)) return; const raw = event.target; if (!(raw instanceof Node)) return; const node = raw instanceof Element ? raw : raw.parentElement; @@ -238,6 +246,7 @@ export const pageScript: (bindingName: string) => void = function pageScript(bin document.addEventListener( 'input', (event) => { + if (fromComposer(event)) return; const el = event.target; if (!(el instanceof Element) || inputKind(el) !== 'text') return; if (isPassword(el)) { @@ -252,6 +261,7 @@ export const pageScript: (bindingName: string) => void = function pageScript(bin document.addEventListener( 'blur', (event) => { + if (fromComposer(event)) return; const el = event.target; if (el instanceof Element) flushInput(el); }, @@ -261,6 +271,7 @@ export const pageScript: (bindingName: string) => void = function pageScript(bin document.addEventListener( 'change', (event) => { + if (fromComposer(event)) return; const el = event.target; if (!el) return; if (el instanceof HTMLSelectElement) { @@ -280,6 +291,7 @@ export const pageScript: (bindingName: string) => void = function pageScript(bin document.addEventListener( 'submit', (event) => { + if (fromComposer(event)) return; const el = event.target; if (el instanceof Element) emit('submit', el, null); }, diff --git a/src/recorder/recording.ts b/src/recorder/recording.ts index 4bdec6d..04e5b39 100644 --- a/src/recorder/recording.ts +++ b/src/recorder/recording.ts @@ -6,11 +6,15 @@ import type { RandomSource } from '../core/ids.ts'; import { randomId } from '../core/ids.ts'; import type { RecordOptions } from '../core/setup.ts'; import { parseActionPayload } from './action-payload.ts'; +import { handleComposerRequest } from './composer-bridge.ts'; +import { COMPOSER_BINDING, composerScriptSource } from './composer-script.ts'; import { htmlToMarkdown } from './html-markdown.ts'; import { type LaunchedBrowser, type LaunchOptions, launchBrowser } from './launch.ts'; import { attachNetwork } from './network.ts'; import { BINDING_NAME, pageScriptSource } from './page-script.ts'; +const PREVIEW_MAX_BYTES = 2_000_000; + export type RecordingOptions = { browser: LaunchOptions; url: string; @@ -18,6 +22,7 @@ export type RecordingOptions = { screenshotsDir: string; random: RandomSource; onEvent: (event: EventInput) => void; + appendEvent?: (event: EventInput) => Promise<{ id: string }>; }; export type Recording = { @@ -41,6 +46,17 @@ function isOpen(page: Page): boolean { return !page.isClosed(); } +function collapseExcerpt(markdown: string): string { + return markdown.replace(/\s+/g, ' ').trim().slice(0, 160); +} + +async function pageViewport(page: Page): Promise<{ width: number; height: number }> { + const size = page.viewportSize(); + if (size !== null) return size; + const [width, height] = await page.evaluate(() => [window.innerWidth, window.innerHeight]); + return { width, height }; +} + export async function startRecording(options: RecordingOptions): Promise { const launched = await launchBrowser(options.browser); try { @@ -81,6 +97,54 @@ async function attachRecording( return current; } + async function emitComposer(event: EventInput): Promise<{ id: string | null }> { + if (options.appendEvent !== undefined) { + return options.appendEvent(event); + } + options.onEvent(event); + return { id: null }; + } + + async function takeScreenshot(page: Page): Promise<{ + file: string; + absolute: string; + bytes: number; + buffer: Buffer; + }> { + await mkdir(options.screenshotsDir, { recursive: true }); + const id = randomId(10, options.random); + const name = `ss_${id}.png`; + const absolute = join(options.screenshotsDir, name); + const buffer = await page.screenshot({ path: absolute, type: 'png' }); + const bytes = buffer.length > 0 ? buffer.length : (await stat(absolute)).size; + return { file: `screenshots/${name}`, absolute, bytes, buffer }; + } + + async function takeSnapshot(page: Page): Promise<{ + event: Extract; + excerpt: string; + }> { + let html = ''; + let title = ''; + let url = ''; + try { + html = await page.content(); + title = await page.title(); + url = page.url(); + } catch { + title = ''; + } + const converted = htmlToMarkdown(html); + const event: Extract = { + kind: 'snapshot', + url, + title, + wordCount: converted.wordCount, + markdown: converted.markdown, + }; + return { event, excerpt: collapseExcerpt(converted.markdown) }; + } + async function attachPage(page: Page): Promise { setCurrent(page); page.on('close', () => { @@ -112,6 +176,11 @@ async function attachRecording( // The document may already be navigating; addInitScript covers the next load. } } + try { + await page.evaluate(composerScriptSource(COMPOSER_BINDING)); + } catch { + // The document may already be navigating; addInitScript covers the next load. + } } if (options.record.actions) { @@ -120,8 +189,52 @@ async function attachRecording( const event = parseActionPayload(payload); if (event !== null) options.onEvent(event); }); + } + await context.exposeBinding(COMPOSER_BINDING, async (source, op: unknown, payload?: unknown) => { + setCurrent(source.page); + return handleComposerRequest(op, payload, { + screenshot: async () => { + const captured = await takeScreenshot(source.page); + await emitComposer({ + kind: 'screenshot', + file: captured.file, + bytes: captured.bytes, + }); + const viewport = await pageViewport(source.page); + const preview = + captured.bytes > PREVIEW_MAX_BYTES + ? null + : `data:image/png;base64,${captured.buffer.toString('base64')}`; + return { + file: captured.file, + width: viewport.width, + height: viewport.height, + preview, + }; + }, + snapshot: async () => { + const { event, excerpt } = await takeSnapshot(source.page); + const { id } = await emitComposer(event); + return { + id, + title: event.title, + wordCount: event.wordCount, + excerpt, + }; + }, + submit: async (kind, text) => { + if (kind === 'note') { + if (text === null) throw new Error('Note text is required.'); + return emitComposer({ kind: 'note', text, author: 'tester' }); + } + return emitComposer({ kind: 'bug', text, author: 'tester' }); + }, + }); + }); + if (options.record.actions) { await context.addInitScript({ content: pageScriptSource(BINDING_NAME) }); } + await context.addInitScript({ content: composerScriptSource(COMPOSER_BINDING) }); if (options.record.network) attachNetwork(context, options.onEvent); if (options.record.console) { context.on('console', (msg) => { @@ -162,38 +275,14 @@ async function attachRecording( }, context, async snapshot() { - const page = currentPage(); - let html = ''; - let title = ''; - let url = ''; - try { - html = await page.content(); - title = await page.title(); - url = page.url(); - } catch { - title = ''; - } - const converted = htmlToMarkdown(html); - const event: EventInput = { - kind: 'snapshot', - url, - title, - wordCount: converted.wordCount, - markdown: converted.markdown, - }; + const { event } = await takeSnapshot(currentPage()); options.onEvent(event); return event; }, async screenshot() { - await mkdir(options.screenshotsDir, { recursive: true }); - const id = randomId(10, options.random); - const name = `ss_${id}.png`; - const absolute = join(options.screenshotsDir, name); - const page = currentPage(); - const buffer = await page.screenshot({ path: absolute, type: 'png' }); - const bytes = buffer.length > 0 ? buffer.length : (await stat(absolute)).size; - options.onEvent({ kind: 'screenshot', file: `screenshots/${name}`, bytes }); - return absolute; + const captured = await takeScreenshot(currentPage()); + options.onEvent({ kind: 'screenshot', file: captured.file, bytes: captured.bytes }); + return captured.absolute; }, async stop() { finish('stopped'); diff --git a/test/recorder.test.ts b/test/recorder.test.ts index 004056d..a126b71 100644 --- a/test/recorder.test.ts +++ b/test/recorder.test.ts @@ -7,6 +7,7 @@ import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { after, test } from 'node:test'; import { fileURLToPath } from 'node:url'; +import type { Page } from 'playwright-core'; import type { EventInput } from '../src/core/events.ts'; import { findInstalledBrowsers } from '../src/recorder/browsers.ts'; import { startRecording } from '../src/recorder/recording.ts'; @@ -280,3 +281,246 @@ test('an unreachable start URL still starts the session and records the failure' await recording.stop(); } }); + +function firstBrowser(t: { skip: (reason?: string) => void }) { + const browser = findInstalledBrowsers({ + platform: process.platform, + env: process.env, + exists: existsSync, + })[0]; + if (browser === undefined) { + t.skip('no Chromium-based browser installed'); + return undefined; + } + return browser; +} + +function collectEvents(): { + events: EventInput[]; + onEvent: (event: EventInput) => void; + appendEvent: (event: EventInput) => Promise<{ id: string }>; +} { + const events: EventInput[] = []; + let n = 0; + return { + events, + onEvent: (event) => { + events.push(event); + }, + appendEvent: async (event) => { + events.push(event); + n += 1; + return { id: `ev_test_${n}` }; + }, + }; +} + +async function openComposer(page: Page): Promise { + await page.click('h1', { button: 'right', modifiers: ['Alt'] }); + await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); +} + +test('composer opens on Alt+right-click and stays closed on plain right-click', { + timeout: 30_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: true, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await page.click('h1', { button: 'right' }); + equal(await page.locator('terrific-composer .panel').isVisible(), false); + + await openComposer(page); + equal(await page.locator('terrific-composer .panel').isVisible(), true); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer Point tool submits a note without recording composer actions', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: true, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await page.locator('#email').waitFor(); + const actionsBefore = collected.events.filter((event) => event.kind === 'action').length; + + await openComposer(page); + await page.locator('terrific-composer .tl', { hasText: 'Point' }).click(); + await page.locator('#email').click(); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('typed note body'); + await page.keyboard.press('Control+Enter'); + + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'note')); + const notes = collected.events.filter((event) => event.kind === 'note'); + equal(notes.length, 1); + if (notes[0]?.kind === 'note') { + equal(notes[0].author, 'tester'); + match(notes[0].text, /\[element /); + match(notes[0].text, /typed note body/); + } + const actionsAfter = collected.events.filter((event) => event.kind === 'action').length; + equal(actionsAfter, actionsBefore); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer Screenshot and Snapshot tools append captures and store a bug with chips', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: true, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + const shot = collected.events.find((event) => event.kind === 'screenshot'); + equal(shot?.kind, 'screenshot'); + if (shot?.kind === 'screenshot') { + const absolute = join(screenshotsDir, shot.file.replace(/^screenshots\//, '')); + ok((await stat(absolute)).size > 0); + } + + await page.locator('terrific-composer .tl', { hasText: 'Snapshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'snapshot')); + equal(await page.locator('terrific-composer .ch.cap').count(), 2); + + await page.locator('terrific-composer .ed').click(); + await page.keyboard.press('Control+Shift+Enter'); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'bug')); + const bugs = collected.events.filter((event) => event.kind === 'bug'); + equal(bugs.length, 1); + if (bugs[0]?.kind === 'bug') { + equal(bugs[0].author, 'tester'); + match(bugs[0].text ?? '', /\[screenshot screenshots\/ss_/); + match(bugs[0].text ?? '', /\[snapshot ev_test_/); + } + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer still opens and submits a note when actions are disabled', { + timeout: 30_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('actions off note'); + await page.keyboard.press('Control+Enter'); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'note')); + const note = collected.events.find((event) => event.kind === 'note'); + equal(note?.kind, 'note'); + if (note?.kind === 'note') { + equal(note.author, 'tester'); + match(note.text, /actions off note/); + } + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer stores an empty bug with null text', { + timeout: 30_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.press('Control+Shift+Enter'); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'bug')); + const bug = collected.events.find((event) => event.kind === 'bug'); + equal(bug?.kind, 'bug'); + if (bug?.kind === 'bug') { + equal(bug.text, null); + equal(bug.author, 'tester'); + } + } finally { + await recording.stop(); + await site.close(); + } +}); From ffe5c7946d4b43455fc0e371daa01d3681f7be78 Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 21:10:50 -0600 Subject: [PATCH 3/7] docs: document the browser note composer Explain the Alt+right-click composer in the README and changelog, and teach the agent skill how to resolve the element, screenshot and snapshot references inside composer notes. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/terrific/SKILL.md | 2 +- .agents/skills/terrific/references/events.md | 12 ++++++++++++ CHANGELOG.md | 4 ++++ README.md | 2 +- 4 files changed, 18 insertions(+), 2 deletions(-) diff --git a/.agents/skills/terrific/SKILL.md b/.agents/skills/terrific/SKILL.md index 7c97a40..b0a2f0a 100644 --- a/.agents/skills/terrific/SKILL.md +++ b/.agents/skills/terrific/SKILL.md @@ -51,7 +51,7 @@ A validation that fails with no evident cause becomes a debug task, and its sess - If you can reproduce the bug yourself (a test, a script, `curl`), do it without asking the user. - Otherwise give the user short numbered steps and wait until they confirm they are done. Mention restarts only when the instrumentation needs one. - While the session runs, mark moments yourself with `terrific note|bug|flag [text]`. - - In a browser session, `terrific screenshot ` captures the page and `terrific snapshot ` saves it as markdown. + - In a browser session, `terrific screenshot ` captures the page and `terrific snapshot ` saves it as markdown. Alt+right-click opens an in-page composer; chip tokens are under "Notes written in the browser" in [references/events.md](references/events.md). - To watch live, run `terrific events --follow` in the background. It ends when the session stops. 7. Stop with `terrific stop `, which prints the summary and writes `context.txt` in the session folder. Omit the id when only one session is recording. - "Session is not recording" means the user already stopped it, so go straight to the evidence. diff --git a/.agents/skills/terrific/references/events.md b/.agents/skills/terrific/references/events.md index c689c1b..b6eeed0 100644 --- a/.agents/skills/terrific/references/events.md +++ b/.agents/skills/terrific/references/events.md @@ -47,3 +47,15 @@ The session folder, printed by `start` and `prompt`, contains: - `events.jsonl`, the lossless source of truth, so grep it directly when filters fall short; - `context.txt`, written when the session stops; - `screenshots/`. + +## Notes written in the browser + +In any browser Terrific records, hold Alt and right-click to open the composer (plain right-click is untouched; works when action recording is off; top frame only). Point adds the clicked element as a chip (Up/Down change level, Enter or click to add, Esc cancels). Screenshot and Snapshot capture the page into the session and add a chip. Note saves with Ctrl+Enter, Bug with Ctrl+Shift+Enter; a bug can be empty. Esc closes and keeps the draft until the page navigates or reloads. + +Composer notes and bugs are stored as normal `note` / `bug` events with `author: 'tester'`. Chips serialize into the event text as: + +- `[element SELECTOR "NAME"]` (name optional): use the CSS selector to locate the element in the page or app code. +- `[screenshot screenshots/ss_.png]`: path relative to the session folder; open that file under `screenshots/`. +- `[snapshot ev_]`: id of the `snapshot` event in `events.jsonl` (or `[snapshot]` when no id was available). Read with `terrific events --type snapshot --json` and match the record whose `id` is that `ev_`. + +Limitations: the draft is lost on navigation or reload; screenshot previews can be blocked by a page's image CSP (the chip still works); iframes and closed shadow roots cannot be pointed into from the top frame. diff --git a/CHANGELOG.md b/CHANGELOG.md index 215c74f..7aa882a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,10 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ## [Unreleased] +### Added + +- Browser note composer: Alt+right-click in a recorded page to write notes and bugs with element, screenshot, and snapshot chips. + ## [1.0.0] - 2026-11-04 ### Fixed diff --git a/README.md b/README.md index 3b40b81..7693d39 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Run `terrific doctor` if setup fails. It checks Node.js, browser discovery, prof 1. Type `/new localhost:5173 "checkout"` in the TUI and confirm the recording setup. 2. Reproduce the issue in the browser Terrific opens. Actions, requests, and console events appear in the live log. -3. Type a note, or use `/bug` and `/flag` to mark a moment. Use `/screenshot` or `/snapshot` to capture the page. +3. Type a note, or use `/bug` and `/flag` to mark a moment. Use `/screenshot` or `/snapshot` to capture the page. In the browser, hold Alt and right-click to open the note composer. 4. Run `/stop` and confirm. The summary shows bugs, errors, failed requests, and the saved session location. 5. Run `/copy` to copy the agent prompt, bugs and errors, or full context. From 70e36843f20ad483a6327ab9b7d9ef07776189d9 Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 22:25:36 -0600 Subject: [PATCH 4/7] feat(recorder): keep the note panel draft in session memory The recording now holds one in-memory draft per session with loadDraft and saveDraft bridge operations, so the page can restore unsent text and chips after a reload or navigation. Drafts are validated strictly, never written to disk, and cleared atomically when a note or bug is saved. Screenshot and snapshot labels are numbered session-wide. Co-Authored-By: Claude Opus 5.5 --- src/recorder/composer-bridge.test.ts | 313 +++++++++++++++++++++++++++ src/recorder/composer-bridge.ts | 164 +++++++++++++- src/recorder/recording.ts | 48 +++- 3 files changed, 519 insertions(+), 6 deletions(-) diff --git a/src/recorder/composer-bridge.test.ts b/src/recorder/composer-bridge.test.ts index 8e40999..2357b5a 100644 --- a/src/recorder/composer-bridge.test.ts +++ b/src/recorder/composer-bridge.test.ts @@ -2,12 +2,24 @@ import { deepEqual, equal, rejects } from 'node:assert/strict'; import { test } from 'node:test'; import { type ComposerBridgeDeps, + type ComposerDraft, type ComposerScreenshotResult, type ComposerSnapshotResult, type ComposerSubmitResult, handleComposerRequest, + parseComposerDraft, } from './composer-bridge.ts'; +function validDraft(overrides: Partial = {}): ComposerDraft { + return { + open: true, + position: { left: 10, top: 20 }, + moved: false, + segments: [{ type: 'text', text: 'hello' }], + ...overrides, + }; +} + function deps(overrides: Partial = {}): ComposerBridgeDeps { return { screenshot: async () => ({ @@ -15,14 +27,18 @@ function deps(overrides: Partial = {}): ComposerBridgeDeps { width: 800, height: 600, preview: null, + label: 'Screenshot 1', }), snapshot: async () => ({ id: 'ev_1', title: 'Page', wordCount: 3, excerpt: 'hello world', + label: 'Snapshot 1', }), submit: async () => ({ id: 'ev_2' }), + loadDraft: async () => ({ draft: null }), + saveDraft: async () => undefined, ...overrides, }; } @@ -33,6 +49,7 @@ test('handleComposerRequest dispatches screenshot', async () => { width: 10, height: 20, preview: 'data:image/png;base64,xx', + label: 'Screenshot 1', }; const result = await handleComposerRequest( 'screenshot', @@ -50,6 +67,7 @@ test('handleComposerRequest dispatches snapshot', async () => { title: 'T', wordCount: 0, excerpt: '', + label: 'Snapshot 1', }; const result = await handleComposerRequest( 'snapshot', @@ -139,3 +157,298 @@ test('handleComposerRequest rejects unknown ops and malformed payloads', async ( await rejects(() => handleComposerRequest('submit', { kind: 'note', text: 1 }, deps()), message); await rejects(() => handleComposerRequest('submit', { kind: 'bug' }, deps()), message); }); + +test('parseComposerDraft round-trips a valid draft and drops extra fields', () => { + const parsed = parseComposerDraft({ + open: true, + position: { left: 1, top: 2, extra: true }, + moved: true, + segments: [ + { type: 'text', text: 'a\nb', extra: 1 }, + { + type: 'element', + selector: '#x', + name: 'X', + tag: 'button', + extra: true, + }, + { + type: 'screenshot', + label: 'Screenshot 1', + file: 'screenshots/ss_abc.png', + width: 100, + height: 50, + preview: 'nope', + }, + { + type: 'snapshot', + label: 'Snapshot 1', + id: 'ev_1', + title: 'Title', + wordCount: 4, + excerpt: 'four words here now', + extra: 'drop', + }, + ], + unused: true, + }); + deepEqual(parsed, { + open: true, + position: { left: 1, top: 2 }, + moved: true, + segments: [ + { type: 'text', text: 'a\nb' }, + { type: 'element', selector: '#x', name: 'X', tag: 'button' }, + { + type: 'screenshot', + label: 'Screenshot 1', + file: 'screenshots/ss_abc.png', + width: 100, + height: 50, + }, + { + type: 'snapshot', + label: 'Snapshot 1', + id: 'ev_1', + title: 'Title', + wordCount: 4, + excerpt: 'four words here now', + }, + ], + }); +}); + +test('parseComposerDraft rejects malformed drafts', () => { + const message = (error: unknown) => + error instanceof Error && error.message === 'Unsupported composer request.'; + const reject = (value: unknown) => { + try { + parseComposerDraft(value); + throw new Error('expected rejection'); + } catch (error) { + if (!message(error)) throw error; + } + }; + + reject(null); + reject([]); + reject({ open: true, position: null, moved: true }); + reject({ open: 'yes', position: null, moved: false, segments: [] }); + reject({ open: true, position: null, moved: 1, segments: [] }); + reject({ open: true, position: { left: 1 }, moved: false, segments: [] }); + reject({ open: true, position: { left: NaN, top: 1 }, moved: false, segments: [] }); + reject({ open: true, position: { left: 1, top: Infinity }, moved: false, segments: [] }); + reject({ open: true, position: 'x', moved: false, segments: [] }); + reject({ open: true, position: null, moved: false, segments: [{ type: 'text' }] }); + reject({ open: true, position: null, moved: false, segments: [{ type: 'widget' }] }); + reject({ + open: true, + position: null, + moved: false, + segments: [ + { type: 'screenshot', label: 'S', file: 'screenshots/../x.png', width: 1, height: 1 }, + ], + }); + reject({ + open: true, + position: null, + moved: false, + segments: [ + { + type: 'screenshot', + label: 'S', + file: '/abs/screenshots/ss_x.png', + width: 1, + height: 1, + }, + ], + }); + reject({ + open: true, + position: null, + moved: false, + segments: [ + { type: 'screenshot', label: 'S', file: 'screenshots/ss_x.jpg', width: 1, height: 1 }, + ], + }); + reject({ + open: true, + position: null, + moved: false, + segments: [{ type: 'element', selector: 'a', name: 'A', tag: 'DIV' }], + }); + reject({ + open: true, + position: null, + moved: false, + segments: [{ type: 'element', selector: 'a', name: 'A', tag: '1div' }], + }); + reject({ + open: true, + position: null, + moved: false, + segments: Array.from({ length: 201 }, () => ({ type: 'text', text: '' })), + }); + reject({ + open: true, + position: null, + moved: false, + segments: [ + { type: 'screenshot', label: 'S', file: 'screenshots/ss_x.png', width: NaN, height: 1 }, + ], + }); + reject({ + open: true, + position: null, + moved: false, + segments: [ + { + type: 'snapshot', + label: 'S', + id: 1, + title: 'T', + wordCount: 0, + excerpt: '', + }, + ], + }); +}); + +test('parseComposerDraft rejects total text over 20000 characters', () => { + try { + parseComposerDraft({ + open: true, + position: null, + moved: false, + segments: [ + { type: 'text', text: 'x'.repeat(10_000) }, + { type: 'text', text: 'y'.repeat(10_001) }, + ], + }); + throw new Error('expected rejection'); + } catch (error) { + equal(error instanceof Error && error.message, 'Note is too long.'); + } +}); + +test('handleComposerRequest saveDraft stores null for empty closed draft', async () => { + let stored: ComposerDraft | null | undefined = validDraft(); + const result = await handleComposerRequest( + 'saveDraft', + { + open: false, + position: null, + moved: false, + segments: [{ type: 'text', text: ' \n ' }], + }, + deps({ + saveDraft: async (draft) => { + stored = draft; + }, + }), + ); + equal(stored, null); + deepEqual(result, { ok: true }); + + await handleComposerRequest( + 'saveDraft', + { + open: false, + position: null, + moved: false, + segments: [], + }, + deps({ + saveDraft: async (draft) => { + stored = draft; + }, + }), + ); + equal(stored, null); + + const openEmpty = validDraft({ open: true, segments: [{ type: 'text', text: ' ' }] }); + await handleComposerRequest( + 'saveDraft', + openEmpty, + deps({ + saveDraft: async (draft) => { + stored = draft; + }, + }), + ); + deepEqual(stored, openEmpty); + + const withElement = validDraft({ + open: false, + segments: [{ type: 'element', selector: '#a', name: 'A', tag: 'a' }], + }); + await handleComposerRequest( + 'saveDraft', + withElement, + deps({ + saveDraft: async (draft) => { + stored = draft; + }, + }), + ); + deepEqual(stored, withElement); +}); + +test('handleComposerRequest loadDraft passes through deps result', async () => { + const draft = { + open: true, + position: null, + moved: false, + segments: [ + { + type: 'screenshot' as const, + label: 'Screenshot 1', + file: 'screenshots/ss_a.png', + width: 1, + height: 2, + preview: 'data:image/png;base64,abc', + }, + ], + }; + const result = await handleComposerRequest( + 'loadDraft', + undefined, + deps({ + loadDraft: async () => ({ draft }), + }), + ); + deepEqual(result, { draft }); +}); + +test('handleComposerRequest clears draft only after successful submit', async () => { + const saved: Array = []; + await handleComposerRequest( + 'submit', + { kind: 'note', text: 'ok' }, + deps({ + saveDraft: async (draft) => { + saved.push(draft); + }, + }), + ); + deepEqual(saved, [null]); + + const failed: Array = []; + await rejects( + () => + handleComposerRequest( + 'submit', + { kind: 'bug', text: 'nope' }, + deps({ + submit: async () => { + throw new Error('append failed'); + }, + saveDraft: async (draft) => { + failed.push(draft); + }, + }), + ), + (error: unknown) => error instanceof Error && error.message === 'append failed', + ); + deepEqual(failed, []); +}); diff --git a/src/recorder/composer-bridge.ts b/src/recorder/composer-bridge.ts index f536c4c..0b09312 100644 --- a/src/recorder/composer-bridge.ts +++ b/src/recorder/composer-bridge.ts @@ -3,6 +3,7 @@ export type ComposerScreenshotResult = { width: number; height: number; preview: string | null; + label: string; }; export type ComposerSnapshotResult = { @@ -10,19 +11,58 @@ export type ComposerSnapshotResult = { title: string; wordCount: number; excerpt: string; + label: string; }; export type ComposerSubmitResult = { id: string | null; }; +export type ComposerSegment = + | { type: 'text'; text: string } + | { type: 'element'; selector: string; name: string; tag: string } + | { type: 'screenshot'; label: string; file: string; width: number; height: number } + | { + type: 'snapshot'; + label: string; + id: string | null; + title: string; + wordCount: number; + excerpt: string; + }; + +export type ComposerDraft = { + open: boolean; + position: { left: number; top: number } | null; + moved: boolean; + segments: ComposerSegment[]; +}; + +export type ComposerDraftWithPreviews = Omit & { + segments: (ComposerSegment & { preview?: string | null })[]; +}; + +export type ComposerLoadDraftResult = { + draft: ComposerDraftWithPreviews | null; +}; + +export type ComposerSaveDraftResult = { + ok: true; +}; + export type ComposerBridgeDeps = { screenshot: () => Promise; snapshot: () => Promise; submit: (kind: 'note' | 'bug', text: string | null) => Promise; + loadDraft: () => Promise; + saveDraft: (draft: ComposerDraft | null) => Promise; }; const MAX_TEXT = 20_000; +const MAX_SEGMENTS = 200; +const MAX_STRING = 2_000; +const FILE_RE = /^screenshots\/ss_[A-Za-z0-9_-]+\.png$/; +const TAG_RE = /^[a-z][a-z0-9-]*$/; function isRecord(value: unknown): value is Record { return typeof value === 'object' && value !== null && !Array.isArray(value); @@ -32,13 +72,127 @@ function unsupported(): never { throw new Error('Unsupported composer request.'); } +function requireString(value: unknown, max = MAX_STRING): string { + if (typeof value !== 'string' || value.length > max) unsupported(); + return value; +} + +function requireFiniteNumber(value: unknown): number { + if (typeof value !== 'number' || !Number.isFinite(value)) unsupported(); + return value; +} + +function parseSegment(value: unknown): ComposerSegment { + if (!isRecord(value)) unsupported(); + const type = value.type; + if (type === 'text') { + if (typeof value.text !== 'string') unsupported(); + return { type: 'text', text: value.text }; + } + if (type === 'element') { + const tag = requireString(value.tag); + if (!TAG_RE.test(tag)) unsupported(); + return { + type: 'element', + selector: requireString(value.selector), + name: requireString(value.name), + tag, + }; + } + if (type === 'screenshot') { + const file = requireString(value.file); + if (!FILE_RE.test(file)) unsupported(); + return { + type: 'screenshot', + label: requireString(value.label), + file, + width: requireFiniteNumber(value.width), + height: requireFiniteNumber(value.height), + }; + } + if (type === 'snapshot') { + const id = value.id; + if (!(id === null || typeof id === 'string')) unsupported(); + if (typeof id === 'string' && id.length > MAX_STRING) unsupported(); + return { + type: 'snapshot', + label: requireString(value.label), + id, + title: requireString(value.title), + wordCount: requireFiniteNumber(value.wordCount), + excerpt: requireString(value.excerpt), + }; + } + unsupported(); +} + +function draftHasContent(draft: ComposerDraft): boolean { + for (const segment of draft.segments) { + if (segment.type === 'text') { + if (segment.text.trim() !== '') return true; + continue; + } + return true; + } + return false; +} + +export function parseComposerDraft(value: unknown): ComposerDraft { + if (!isRecord(value)) unsupported(); + if (typeof value.open !== 'boolean') unsupported(); + if (typeof value.moved !== 'boolean') unsupported(); + + let position: ComposerDraft['position']; + if (value.position === null) { + position = null; + } else if (isRecord(value.position)) { + position = { + left: requireFiniteNumber(value.position.left), + top: requireFiniteNumber(value.position.top), + }; + } else { + unsupported(); + } + + if (!Array.isArray(value.segments)) unsupported(); + if (value.segments.length > MAX_SEGMENTS) unsupported(); + + const segments = value.segments.map(parseSegment); + let textChars = 0; + for (const segment of segments) { + if (segment.type === 'text') textChars += segment.text.length; + } + if (textChars > MAX_TEXT) { + throw new Error('Note is too long.'); + } + + return { + open: value.open, + position, + moved: value.moved, + segments, + }; +} + export async function handleComposerRequest( op: unknown, payload: unknown, deps: ComposerBridgeDeps, -): Promise { +): Promise< + | ComposerScreenshotResult + | ComposerSnapshotResult + | ComposerSubmitResult + | ComposerLoadDraftResult + | ComposerSaveDraftResult +> { if (op === 'screenshot') return deps.screenshot(); if (op === 'snapshot') return deps.snapshot(); + if (op === 'loadDraft') return deps.loadDraft(); + if (op === 'saveDraft') { + const draft = parseComposerDraft(payload); + await deps.saveDraft(!draftHasContent(draft) && !draft.open ? null : draft); + return { ok: true }; + } if (op !== 'submit') unsupported(); if (!isRecord(payload)) unsupported(); @@ -55,9 +209,13 @@ export async function handleComposerRequest( if (text === null || text.trim() === '') { throw new Error('Note text is required.'); } - return deps.submit('note', text); + const result = await deps.submit('note', text); + await deps.saveDraft(null); + return result; } const stored = text === null || text.trim() === '' ? null : text; - return deps.submit('bug', stored); + const result = await deps.submit('bug', stored); + await deps.saveDraft(null); + return result; } diff --git a/src/recorder/recording.ts b/src/recorder/recording.ts index 04e5b39..e3c072a 100644 --- a/src/recorder/recording.ts +++ b/src/recorder/recording.ts @@ -1,12 +1,16 @@ -import { mkdir, stat } from 'node:fs/promises'; -import { join } from 'node:path'; +import { mkdir, readFile, stat } from 'node:fs/promises'; +import { basename, join } from 'node:path'; import type { BrowserContext, Page } from 'playwright-core'; import type { EventInput } from '../core/events.ts'; import type { RandomSource } from '../core/ids.ts'; import { randomId } from '../core/ids.ts'; import type { RecordOptions } from '../core/setup.ts'; import { parseActionPayload } from './action-payload.ts'; -import { handleComposerRequest } from './composer-bridge.ts'; +import { + type ComposerDraft, + type ComposerSegment, + handleComposerRequest, +} from './composer-bridge.ts'; import { COMPOSER_BINDING, composerScriptSource } from './composer-script.ts'; import { htmlToMarkdown } from './html-markdown.ts'; import { type LaunchedBrowser, type LaunchOptions, launchBrowser } from './launch.ts'; @@ -74,6 +78,9 @@ async function attachRecording( ): Promise { const { context } = launched; let current = launched.page; + let composerDraft: ComposerDraft | null = null; + let screenshotLabelCount = 0; + let snapshotLabelCount = 0; let outcome: 'stopped' | 'browser-closed' | null = null; let resolveClosed: ((reason: 'stopped' | 'browser-closed') => void) | undefined; const closed = new Promise<'stopped' | 'browser-closed'>((resolve) => { @@ -120,6 +127,30 @@ async function attachRecording( return { file: `screenshots/${name}`, absolute, bytes, buffer }; } + async function screenshotPreview(file: string): Promise { + const absolute = join(options.screenshotsDir, basename(file)); + try { + const info = await stat(absolute); + if (!info.isFile() || info.size > PREVIEW_MAX_BYTES) return null; + const buffer = await readFile(absolute); + return `data:image/png;base64,${buffer.toString('base64')}`; + } catch { + return null; + } + } + + async function draftWithPreviews( + draft: ComposerDraft, + ): Promise { + const segments = await Promise.all( + draft.segments.map(async (segment) => { + if (segment.type !== 'screenshot') return segment; + return { ...segment, preview: await screenshotPreview(segment.file) }; + }), + ); + return { ...draft, segments }; + } + async function takeSnapshot(page: Page): Promise<{ event: Extract; excerpt: string; @@ -205,21 +236,25 @@ async function attachRecording( captured.bytes > PREVIEW_MAX_BYTES ? null : `data:image/png;base64,${captured.buffer.toString('base64')}`; + screenshotLabelCount += 1; return { file: captured.file, width: viewport.width, height: viewport.height, preview, + label: `Screenshot ${screenshotLabelCount}`, }; }, snapshot: async () => { const { event, excerpt } = await takeSnapshot(source.page); const { id } = await emitComposer(event); + snapshotLabelCount += 1; return { id, title: event.title, wordCount: event.wordCount, excerpt, + label: `Snapshot ${snapshotLabelCount}`, }; }, submit: async (kind, text) => { @@ -229,6 +264,13 @@ async function attachRecording( } return emitComposer({ kind: 'bug', text, author: 'tester' }); }, + loadDraft: async () => { + if (composerDraft === null) return { draft: null }; + return { draft: await draftWithPreviews(composerDraft) }; + }, + saveDraft: async (draft) => { + composerDraft = draft; + }, }); }); if (options.record.actions) { From 151d4745373f618aaf9b410436ba1e4074b92bb8 Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 22:36:28 -0600 Subject: [PATCH 5/7] feat(recorder): restore the note panel draft after reloads and navigation The note panel saves its draft to the session as the tester types and when the page hides, and restores it on every new page. An open panel reappears at the same position without taking focus. Element chips whose selector is missing on the current page are shown as unavailable but still serialize. Screenshot and snapshot labels come from the session so numbering continues. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/terrific/references/events.md | 6 +- CHANGELOG.md | 2 +- README.md | 2 +- src/recorder/composer-script.ts | 353 +++++++++++++++++-- test/recorder.test.ts | 234 ++++++++++++ 5 files changed, 568 insertions(+), 29 deletions(-) diff --git a/.agents/skills/terrific/references/events.md b/.agents/skills/terrific/references/events.md index b6eeed0..0bb0aea 100644 --- a/.agents/skills/terrific/references/events.md +++ b/.agents/skills/terrific/references/events.md @@ -50,12 +50,12 @@ The session folder, printed by `start` and `prompt`, contains: ## Notes written in the browser -In any browser Terrific records, hold Alt and right-click to open the composer (plain right-click is untouched; works when action recording is off; top frame only). Point adds the clicked element as a chip (Up/Down change level, Enter or click to add, Esc cancels). Screenshot and Snapshot capture the page into the session and add a chip. Note saves with Ctrl+Enter, Bug with Ctrl+Shift+Enter; a bug can be empty. Esc closes and keeps the draft until the page navigates or reloads. +In any browser Terrific records, hold Alt and right-click to open the Note panel (plain right-click is untouched; works when action recording is off; top frame only). Point adds the clicked element as a chip (Up/Down change level, Enter or click to add, Esc cancels). Screenshot and Snapshot capture the page into the session and add a chip. Note saves with Ctrl+Enter, Bug with Ctrl+Shift+Enter; a bug can be empty. Esc closes and keeps the draft. -Composer notes and bugs are stored as normal `note` / `bug` events with `author: 'tester'`. Chips serialize into the event text as: +Note panel notes and bugs are stored as normal `note` / `bug` events with `author: 'tester'`. Chips serialize into the event text as: - `[element SELECTOR "NAME"]` (name optional): use the CSS selector to locate the element in the page or app code. - `[screenshot screenshots/ss_.png]`: path relative to the session folder; open that file under `screenshots/`. - `[snapshot ev_]`: id of the `snapshot` event in `events.jsonl` (or `[snapshot]` when no id was available). Read with `terrific events --type snapshot --json` and match the record whose `id` is that `ev_`. -Limitations: the draft is lost on navigation or reload; screenshot previews can be blocked by a page's image CSP (the chip still works); iframes and closed shadow roots cannot be pointed into from the top frame. +Limitations: the draft (unsent text and chips) lives in memory for the whole session, survives reloads, navigation and new tabs, and is discarded when the session stops; nothing is written to disk until it is sent. Screenshot previews can be blocked by a page's image CSP (the chip still works); iframes and closed shadow roots cannot be pointed into from the top frame. diff --git a/CHANGELOG.md b/CHANGELOG.md index 7aa882a..1300f8f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,7 +8,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), ### Added -- Browser note composer: Alt+right-click in a recorded page to write notes and bugs with element, screenshot, and snapshot chips. +- Browser note panel: Alt+right-click in a recorded page to write notes and bugs with element, screenshot, and snapshot chips. Unsent drafts survive reloads and navigation for the rest of the session. ## [1.0.0] - 2026-11-04 diff --git a/README.md b/README.md index 7693d39..13b399f 100644 --- a/README.md +++ b/README.md @@ -56,7 +56,7 @@ Run `terrific doctor` if setup fails. It checks Node.js, browser discovery, prof 1. Type `/new localhost:5173 "checkout"` in the TUI and confirm the recording setup. 2. Reproduce the issue in the browser Terrific opens. Actions, requests, and console events appear in the live log. -3. Type a note, or use `/bug` and `/flag` to mark a moment. Use `/screenshot` or `/snapshot` to capture the page. In the browser, hold Alt and right-click to open the note composer. +3. Type a note, or use `/bug` and `/flag` to mark a moment. Use `/screenshot` or `/snapshot` to capture the page. In the browser, hold Alt and right-click to open the note panel. 4. Run `/stop` and confirm. The summary shows bugs, errors, failed requests, and the saved session location. 5. Run `/copy` to copy the agent prompt, bugs and errors, or full context. diff --git a/src/recorder/composer-script.ts b/src/recorder/composer-script.ts index 2709450..88bb7db 100644 --- a/src/recorder/composer-script.ts +++ b/src/recorder/composer-script.ts @@ -76,6 +76,7 @@ button:disabled{cursor:default;opacity:.4} .ch.el{background:rgba(99,102,241,.15);border:1px solid rgba(99,102,241,.1);color:#a5b4fc} .ch.cap{background:rgba(255,255,255,.06);border:1px solid rgba(255,255,255,.1);color:#e4e4e7;font-family:Inter,system-ui,sans-serif} .ch.cap svg{color:#22d3ee} +.ch.gone{opacity:.45;border-style:dashed} .ch:hover{filter:brightness(1.25)} .ch .rm{display:none;width:14px;height:14px;margin:0 -2px 0 1px;border:0;padding:0;border-radius:3px;background:transparent;color:inherit;place-items:center} .ch:hover .rm{display:inline-grid} @@ -219,7 +220,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s layer.append(ref, hl, panel, pop, toast); root.append(layer); type Chip = - | { kind: 'element'; el: Element; selector: string; name: string } + | { kind: 'element'; el: Element | null; selector: string; name: string; tag: string } | { kind: 'screenshot'; label: string; @@ -236,11 +237,34 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s wordCount: number; excerpt: string; }; + type DraftSegment = + | { type: 'text'; text: string } + | { type: 'element'; selector: string; name: string; tag: string } + | { type: 'screenshot'; label: string; file: string; width: number; height: number } + | { + type: 'snapshot'; + label: string; + id: string | null; + title: string; + wordCount: number; + excerpt: string; + }; + type Draft = { + open: boolean; + position: { left: number; top: number } | null; + moved: boolean; + segments: DraftSegment[]; + }; + type DraftWithPreviews = Omit & { + segments: (DraftSegment & { preview?: string | null })[]; + }; const chipData = new WeakMap(); - const counters = { screenshot: 0, snapshot: 0 }; let savedRange: Range | null = null; let busy = false; let moved = false; + let dirty = false; + let restoring = false; + let saveTimer: ReturnType | undefined; let toastTimer: ReturnType | undefined; const selection = () => 'getSelection' in root && typeof root.getSelection === 'function' @@ -331,6 +355,25 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s ? !/\s$/.test((prev as Text).data) : prev.nodeName !== 'BR'; } + function resolveElement(selector: string): Element | null { + try { + const found = document.querySelector(selector); + if (!found || found === host || host.contains(found)) return null; + return found; + } catch { + return null; + } + } + function decorateElementChip(chip: HTMLElement, data: Extract) { + data.el = resolveElement(data.selector); + if (data.el) { + chip.classList.remove('gone'); + chip.title = data.selector; + } else { + chip.classList.add('gone'); + chip.title = `${data.selector} (not on this page)`; + } + } function insertChip(chip: HTMLElement) { ed.focus({ preventScroll: true }); const r = rangeInEditor(); @@ -345,6 +388,8 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s caret.collapse(true); placeCaret(caret); update(); + dirty = true; + saveDraftNow(); } function makeChip(data: Chip, label: string, icon?: string[]) { const chip = h('span', { @@ -359,16 +404,16 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s ]), ); chipData.set(chip, data); + if (data.kind === 'element') decorateElementChip(chip, data); return chip; } function addElement(el: Element | null) { if (!usable(el)) return; const selector = selectorFor(el); const chip = makeChip( - { kind: 'element', el, selector, name: accessibleName(el) }, + { kind: 'element', el, selector, name: accessibleName(el), tag: el.localName }, `<${el.localName}>`, ); - chip.title = selector; insertChip(chip); } document.addEventListener('selectionchange', () => { @@ -379,6 +424,8 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s ed.addEventListener('input', () => { hideError(); update(); + dirty = true; + scheduleSave(); }); ed.addEventListener('paste', (e) => { e.preventDefault(); @@ -397,6 +444,8 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s hidePreview(); update(); ed.focus(); + dirty = true; + saveDraftNow(); }); let pointing = false, chain: Element[] = [], @@ -549,6 +598,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s hd.removeEventListener('pointermove', move); hd.removeEventListener('pointerup', up); hd.removeEventListener('pointercancel', up); + saveDraftNow(); }; hd.addEventListener('pointermove', move); hd.addEventListener('pointerup', up); @@ -565,7 +615,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s const data = chipData.get(chip); if (!data) return; if (data.kind === 'element') { - if (!data.el.isConnected) return; + if (!data.el?.isConnected) return; const r = data.el.getBoundingClientRect(); Object.assign(ref.style, { left: `${r.left - 3}px`, @@ -624,7 +674,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s hideError(); hidePreview(); const btn = kind === 'screenshot' ? shot : snap, - label = btn.text.textContent; + buttonLabel = btn.text.textContent; busy = true; update(); btn.text.textContent = kind === 'screenshot' ? 'Capturing…' : 'Reading page…'; @@ -632,24 +682,51 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s let chip: HTMLElement; if (kind === 'screenshot') { layer.classList.add('capturing'); - let res: { file: string; width: number; height: number; preview: string | null }; + let res: { + file: string; + width: number; + height: number; + preview: string | null; + label: string; + }; try { await frame(); res = await bridge('screenshot'); } finally { layer.classList.remove('capturing'); } - const name = `Screenshot ${++counters.screenshot}`; - chip = makeChip({ kind: 'screenshot', label: name, ...res }, name, icons.cam); + chip = makeChip( + { + kind: 'screenshot', + label: res.label, + file: res.file, + width: res.width, + height: res.height, + preview: res.preview, + }, + res.label, + icons.cam, + ); } else { const res = await bridge<{ id: string | null; title: string; wordCount: number; excerpt: string; + label: string; }>('snapshot'); - const name = `Snapshot ${++counters.snapshot}`; - chip = makeChip({ kind: 'snapshot', label: name, ...res }, name, icons.scan); + chip = makeChip( + { + kind: 'snapshot', + label: res.label, + id: res.id, + title: res.title, + wordCount: res.wordCount, + excerpt: res.excerpt, + }, + res.label, + icons.scan, + ); } busy = false; insertChip(chip); @@ -659,7 +736,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s ); } finally { busy = false; - btn.text.textContent = label; + btn.text.textContent = buttonLabel; update(); } } @@ -691,11 +768,205 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s function hideError() { err.hidden = true; } + function currentPosition(): { left: number; top: number } | null { + const left = panel.style.left; + const top = panel.style.top; + if (!left || !top) return null; + const leftN = Number.parseFloat(left); + const topN = Number.parseFloat(top); + if (!Number.isFinite(leftN) || !Number.isFinite(topN)) return null; + return { left: leftN, top: topN }; + } + function buildSegments(): DraftSegment[] { + const segments: DraftSegment[] = []; + let text = ''; + const flush = () => { + if (text === '') return; + segments.push({ type: 'text', text }); + text = ''; + }; + const walk = (node: Node) => { + for (const n of node.childNodes) { + if (n.nodeType === Node.TEXT_NODE) { + text += (n as Text).data; + continue; + } + if (n.nodeName === 'BR') { + text += '\n'; + continue; + } + if (n instanceof Element && n.classList.contains('ch')) { + flush(); + const d = chipData.get(n); + if (!d) continue; + if (d.kind === 'element') { + segments.push({ + type: 'element', + selector: d.selector, + name: d.name, + tag: d.tag, + }); + } else if (d.kind === 'screenshot') { + segments.push({ + type: 'screenshot', + label: d.label, + file: d.file, + width: d.width, + height: d.height, + }); + } else { + segments.push({ + type: 'snapshot', + label: d.label, + id: d.id, + title: d.title, + wordCount: d.wordCount, + excerpt: d.excerpt, + }); + } + continue; + } + if (n instanceof Element) { + if (n.nodeName === 'DIV' && text && !text.endsWith('\n')) text += '\n'; + walk(n); + } + } + }; + walk(ed); + flush(); + return segments; + } + function buildDraft(): Draft { + return { + open: !panel.hidden, + position: currentPosition(), + moved, + segments: buildSegments(), + }; + } + function cancelPendingSave() { + if (saveTimer === undefined) return; + clearTimeout(saveTimer); + saveTimer = undefined; + } + function saveDraftNow() { + if (restoring) return; + cancelPendingSave(); + void bridge('saveDraft', buildDraft()).catch(() => {}); + } + function scheduleSave() { + if (restoring) return; + cancelPendingSave(); + saveTimer = setTimeout(() => { + saveTimer = undefined; + saveDraftNow(); + }, 300); + } + function placeDefault() { + const r = panel.getBoundingClientRect(); + panel.style.left = `${clamp(innerWidth - r.width - 20, 8, Math.max(8, innerWidth - r.width - 8))}px`; + panel.style.top = `${clamp(innerHeight - r.height - 20, 8, Math.max(8, innerHeight - r.height - 8))}px`; + } + function placeAt(position: { left: number; top: number } | null) { + if (position) { + panel.style.left = `${position.left}px`; + panel.style.top = `${position.top}px`; + } else { + placeDefault(); + } + keepInView(); + } + function appendTextSegment(value: string) { + const parts = value.split('\n'); + for (let i = 0; i < parts.length; i++) { + if (i > 0) ed.append(document.createElement('br')); + const part = parts[i]; + if (part) ed.append(part); + } + } + function applyDraft(draft: DraftWithPreviews) { + ed.replaceChildren(); + savedRange = null; + for (const segment of draft.segments) { + if (segment.type === 'text') { + appendTextSegment(segment.text); + continue; + } + if (segment.type === 'element') { + const chip = makeChip( + { + kind: 'element', + el: null, + selector: segment.selector, + name: segment.name, + tag: segment.tag, + }, + `<${segment.tag}>`, + ); + ed.append(chip, document.createTextNode(' ')); + continue; + } + if (segment.type === 'screenshot') { + const chip = makeChip( + { + kind: 'screenshot', + label: segment.label, + file: segment.file, + width: segment.width, + height: segment.height, + preview: segment.preview ?? null, + }, + segment.label, + icons.cam, + ); + ed.append(chip, document.createTextNode(' ')); + continue; + } + const chip = makeChip( + { + kind: 'snapshot', + label: segment.label, + id: segment.id, + title: segment.title, + wordCount: segment.wordCount, + excerpt: segment.excerpt, + }, + segment.label, + icons.scan, + ); + ed.append(chip, document.createTextNode(' ')); + } + moved = draft.moved; + update(); + } + async function loadAndApplyDraft(): Promise { + if (dirty) return null; + const fn = w[bindingName]; + if (typeof fn !== 'function') return null; + restoring = true; + try { + const result = (await bridge('loadDraft')) as { draft: DraftWithPreviews | null }; + if (dirty || !result.draft) return result.draft; + applyDraft(result.draft); + return result.draft; + } catch { + return null; + } finally { + restoring = false; + } + } + function showPanelFromDraft(draft: DraftWithPreviews) { + if (!host.isConnected) document.documentElement.append(host); + stopPoint(); + panel.hidden = false; + placeAt(draft.position); + } function close() { stopPoint(); hidePreview(); hideError(); panel.hidden = true; + saveDraftNow(); } function showToast(kind: 'note' | 'bug') { toast.className = `toast${kind === 'bug' ? ' bug' : ''}`; @@ -714,6 +985,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s stopPoint(); hideError(); hidePreview(); + cancelPendingSave(); const btn = kind === 'bug' ? bug : note; const text = serialize() .replace(/[ \t]+\n/g, '\n') @@ -726,6 +998,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s await bridge('submit', { kind, text: text || null }); ed.replaceChildren(); savedRange = null; + dirty = false; close(); showToast(kind); } catch (error) { @@ -754,25 +1027,57 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s close(); } }); + function flushSave() { + if (restoring) return; + cancelPendingSave(); + const fn = w[bindingName]; + if (typeof fn !== 'function') return; + void bridge('saveDraft', buildDraft()).catch(() => {}); + } + window.addEventListener('pagehide', flushSave); + document.addEventListener('visibilitychange', () => { + if (document.visibilityState === 'hidden') flushSave(); + }); update(); + const boot = (async () => { + const ready = + document.readyState !== 'loading' + ? Promise.resolve() + : new Promise((resolve) => { + document.addEventListener('DOMContentLoaded', () => resolve(), { once: true }); + }); + await ready; + const draft = await loadAndApplyDraft(); + if (!draft?.open) return; + showPanelFromDraft(draft); + })(); window.addEventListener( 'contextmenu', (e) => { if (!e.altKey || isOurs(e)) return; e.preventDefault(); e.stopImmediatePropagation(); - if (!host.isConnected) document.documentElement.append(host); - if (pointing) stopPoint(); - const wasOpen = !panel.hidden; - panel.hidden = false; - if (!wasOpen && !moved) { - const r = panel.getBoundingClientRect(); - panel.style.left = `${clamp(e.clientX + 12, 8, Math.max(8, innerWidth - r.width - 8))}px`; - panel.style.top = `${e.clientY + 12 + r.height <= innerHeight - 8 ? e.clientY + 12 : clamp(e.clientY - r.height - 12, 8, Math.max(8, innerHeight - r.height - 8))}px`; - } - keepInView(); - ed.focus({ preventScroll: true }); - placeCaret(rangeInEditor()); + void (async () => { + await boot; + if (!host.isConnected) document.documentElement.append(host); + if (pointing) stopPoint(); + const wasOpen = !panel.hidden; + if (!wasOpen) { + const draft = await loadAndApplyDraft(); + panel.hidden = false; + if (!moved) { + const r = panel.getBoundingClientRect(); + panel.style.left = `${clamp(e.clientX + 12, 8, Math.max(8, innerWidth - r.width - 8))}px`; + panel.style.top = `${e.clientY + 12 + r.height <= innerHeight - 8 ? e.clientY + 12 : clamp(e.clientY - r.height - 12, 8, Math.max(8, innerHeight - r.height - 8))}px`; + } else if (draft?.position) { + placeAt(draft.position); + } + keepInView(); + saveDraftNow(); + } + ed.focus({ preventScroll: true }); + placeCaret(rangeInEditor()); + })(); }, true, ); diff --git a/test/recorder.test.ts b/test/recorder.test.ts index a126b71..7bd2e1d 100644 --- a/test/recorder.test.ts +++ b/test/recorder.test.ts @@ -524,3 +524,237 @@ test('composer stores an empty bug with null text', { await site.close(); } }); + +test('composer draft survives reload with chips and without stealing focus', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await page.locator('#email').waitFor(); + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('draft survives reload'); + await page.locator('terrific-composer .tl', { hasText: 'Point' }).click(); + await page.locator('#email').click(); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + equal(await page.locator('terrific-composer .ch.el').count(), 1); + equal(await page.locator('terrific-composer .ch.cap').count(), 1); + + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); + match( + (await page.locator('terrific-composer .ed').textContent()) ?? '', + /draft survives reload/, + ); + equal(await page.locator('terrific-composer .ch.el').count(), 1); + equal(await page.locator('terrific-composer .ch.cap').count(), 1); + equal( + await page.evaluate(() => document.activeElement?.localName === 'terrific-composer'), + false, + ); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer draft survives navigation and marks missing element chips gone', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await page.locator('#email').waitFor(); + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('draft on page two'); + await page.locator('terrific-composer .tl', { hasText: 'Point' }).click(); + await page.locator('#email').click(); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + + await page.goto(`${site.url}/page2.html`, { waitUntil: 'domcontentloaded' }); + await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); + match((await page.locator('terrific-composer .ed').textContent()) ?? '', /draft on page two/); + equal(await page.locator('terrific-composer .ch.el').count(), 1); + equal(await page.locator('terrific-composer .ch.el.gone').count(), 1); + equal(await page.locator('terrific-composer .ch.cap').count(), 1); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer submit after reload clears the draft for the next open', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await page.locator('#email').waitFor(); + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('submit after reload'); + await page.locator('terrific-composer .tl', { hasText: 'Point' }).click(); + await page.locator('#email').click(); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.press('Control+Enter'); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'note')); + const notes = collected.events.filter((event) => event.kind === 'note'); + equal(notes.length, 1); + if (notes[0]?.kind === 'note') { + match(notes[0].text, /submit after reload/); + match(notes[0].text, /\[element /); + match(notes[0].text, /\[screenshot screenshots\/ss_/); + } + + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('h1').waitFor(); + equal(await page.locator('terrific-composer .panel').isVisible(), false); + await openComposer(page); + equal((await page.locator('terrific-composer .ed').textContent())?.trim(), ''); + equal(await page.locator('terrific-composer .ch').count(), 0); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer Esc close keeps draft hidden across reload until reopened', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('closed draft text'); + await page.keyboard.press('Escape'); + equal(await page.locator('terrific-composer .panel').isVisible(), false); + + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('h1').waitFor(); + equal(await page.locator('terrific-composer .panel').isVisible(), false); + await openComposer(page); + match((await page.locator('terrific-composer .ed').textContent()) ?? '', /closed draft text/); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer screenshot labels continue across reload', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + match((await page.locator('terrific-composer .ch.cap').textContent()) ?? '', /Screenshot 1/); + + await page.reload({ waitUntil: 'domcontentloaded' }); + await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); + match((await page.locator('terrific-composer .ch.cap').textContent()) ?? '', /Screenshot 1/); + await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); + await waitFor( + collected.events, + (seen) => seen.filter((event) => event.kind === 'screenshot').length >= 2, + ); + const labels = await page.locator('terrific-composer .ch.cap').allTextContents(); + equal( + labels.some((label) => /Screenshot 1/.test(label)), + true, + ); + equal( + labels.some((label) => /Screenshot 2/.test(label)), + true, + ); + } finally { + await recording.stop(); + await site.close(); + } +}); From 0c9245659f02c86d99f791cd719781c47d5b46c6 Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 22:46:56 -0600 Subject: [PATCH 6/7] feat(recorder): soften note panel transitions and drop the save toast The note panel fades in and out quickly, including around screenshots, where it is hidden outright once faded so it never lands in the image. Saving now confirms in place by turning the button into Saved before the panel fades out, with a screen-reader status instead of the corner toast. Reduced motion skips the transitions. Co-Authored-By: Claude Opus 5.5 --- src/recorder/composer-script.ts | 106 +++++++++++++++++++++++--------- test/recorder.test.ts | 3 +- 2 files changed, 78 insertions(+), 31 deletions(-) diff --git a/src/recorder/composer-script.ts b/src/recorder/composer-script.ts index 88bb7db..0a5f6a0 100644 --- a/src/recorder/composer-script.ts +++ b/src/recorder/composer-script.ts @@ -52,6 +52,7 @@ export const composerScript: (bindingName: string) => void = function composerSc 'M4.04 4.69a.5.5 0 0 1 .65-.65l16 6.5a.5.5 0 0 1-.06.95l-6.12 1.58a2 2 0 0 0-1.44 1.44l-1.58 6.12a.5.5 0 0 1-.95.07z', ], x: ['M18 6 6 18M6 6l12 12'], + check: ['M20 6 9 17l-5-5'], }; const css = ` :host{all:initial} @@ -59,10 +60,14 @@ export const composerScript: (bindingName: string) => void = function composerSc [hidden]{display:none!important} .layer{position:fixed;inset:0;pointer-events:none;z-index:2147483646;font:500 13px/1.4 Inter,system-ui,"Segoe UI",sans-serif;color:#e4e4e7;-webkit-font-smoothing:antialiased} .layer.capturing{visibility:hidden} +.sr{position:absolute;width:1px;height:1px;overflow:hidden;clip-path:inset(50%);white-space:nowrap} button{font:inherit;cursor:pointer} button:focus-visible{outline:2px solid rgba(255,255,255,.45);outline-offset:1px} button:disabled{cursor:default;opacity:.4} -.panel{position:fixed;pointer-events:auto;width:366px;max-width:calc(100vw - 16px);background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,.5);overflow:hidden} +.panel.sent button:disabled{opacity:1} +.panel{position:fixed;pointer-events:auto;width:366px;max-width:calc(100vw - 16px);background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:16px;box-shadow:0 25px 50px -12px rgba(0,0,0,.5);overflow:hidden;transition:opacity 160ms cubic-bezier(.2,.8,.2,1),transform 160ms cubic-bezier(.2,.8,.2,1)} +.panel.faded{opacity:0;transform:scale(.97)} +@media (prefers-reduced-motion:reduce){.panel{transition:none}} .hd{display:flex;align-items:center;gap:8px;height:38px;padding:0 6px 0 12px;background:rgba(24,24,27,.8);border-bottom:1px solid rgba(255,255,255,.05);cursor:grab;color:#52525b;user-select:none;touch-action:none} .hd.dragging{cursor:grabbing} .hd h2{margin:0;font:700 11px Inter,system-ui,sans-serif;letter-spacing:.06em;text-transform:uppercase;color:#fff} @@ -111,10 +116,6 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s .pop .sn{padding:4px 4px 2px;font:400 12px/1.5 Inter,system-ui,sans-serif;color:#a1a1aa} .pop .sn b{display:block;color:#e4e4e7;font-weight:500;margin-bottom:2px} .pop .excerpt{margin-top:4px;color:#71717a} -.toast{position:fixed;right:20px;bottom:20px;pointer-events:auto;display:flex;align-items:center;gap:8px;padding:10px 14px;background:#18181b;border:1px solid rgba(255,255,255,.1);border-radius:12px;box-shadow:0 12px 30px rgba(0,0,0,.4);color:#e4e4e7} -.toast svg{color:#a5b4fc} -.toast.bug svg{color:#f87171} -@media (max-width:420px){.toast{right:12px;left:12px;bottom:12px}} `; const host = document.createElement('terrific-composer'); // Init scripts can run before exists; the Alt+right-click handler attaches the host on demand. @@ -216,8 +217,9 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s h('div', { class: 'ft' }, [idle, pointingHint]), ); const pop = h('div', { class: 'pop', hidden: '' }); - const toast = h('div', { class: 'toast', role: 'status', 'aria-live': 'polite', hidden: '' }); - layer.append(ref, hl, panel, pop, toast); + // Screen-reader-only confirmation; the visible feedback is the button turning into "Saved". + const status = h('span', { class: 'sr', role: 'status', 'aria-live': 'polite' }); + layer.append(ref, hl, panel, pop, status); root.append(layer); type Chip = | { kind: 'element'; el: Element | null; selector: string; name: string; tag: string } @@ -265,7 +267,31 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s let dirty = false; let restoring = false; let saveTimer: ReturnType | undefined; - let toastTimer: ReturnType | undefined; + // Set between a successful submit and the editor being cleared, so no save can resurrect a sent draft. + let sealed = false; + let closeTimer: ReturnType | undefined; + const FADE_MS = 170; + const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); + const reducedMotion = () => + typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches; + function animateIn() { + if (reducedMotion()) return; + panel.classList.add('faded'); + // Commit the faded state before removing it so the transition runs. + void panel.offsetWidth; + panel.classList.remove('faded'); + } + async function fadeOut() { + if (panel.hidden || reducedMotion()) return; + panel.classList.add('faded'); + await wait(FADE_MS); + } + function cancelClose() { + if (closeTimer === undefined) return; + clearTimeout(closeTimer); + closeTimer = undefined; + panel.classList.remove('faded'); + } const selection = () => 'getSelection' in root && typeof root.getSelection === 'function' ? (root.getSelection as () => Selection | null)() @@ -681,7 +707,6 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s try { let chip: HTMLElement; if (kind === 'screenshot') { - layer.classList.add('capturing'); let res: { file: string; width: number; @@ -690,10 +715,14 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s label: string; }; try { + // Fade out, then hide outright so a half-transparent panel never lands in the image. + await fadeOut(); + layer.classList.add('capturing'); await frame(); res = await bridge('screenshot'); } finally { layer.classList.remove('capturing'); + panel.classList.remove('faded'); } chip = makeChip( { @@ -850,12 +879,12 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s saveTimer = undefined; } function saveDraftNow() { - if (restoring) return; + if (restoring || sealed) return; cancelPendingSave(); void bridge('saveDraft', buildDraft()).catch(() => {}); } function scheduleSave() { - if (restoring) return; + if (restoring || sealed) return; cancelPendingSave(); saveTimer = setTimeout(() => { saveTimer = undefined; @@ -960,25 +989,25 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s stopPoint(); panel.hidden = false; placeAt(draft.position); + animateIn(); } function close() { stopPoint(); hidePreview(); hideError(); - panel.hidden = true; - saveDraftNow(); - } - function showToast(kind: 'note' | 'bug') { - toast.className = `toast${kind === 'bug' ? ' bug' : ''}`; - toast.replaceChildren( - svg(kind === 'bug' ? icons.bug : icons.msg), - h('span', {}, [`${kind === 'bug' ? 'Bug' : 'Note'} saved to the session`]), - ); - toast.hidden = false; - clearTimeout(toastTimer); - toastTimer = setTimeout(() => { - toast.hidden = true; - }, 2600); + if (panel.hidden || closeTimer !== undefined) return; + const finish = () => { + closeTimer = undefined; + panel.hidden = true; + panel.classList.remove('faded'); + saveDraftNow(); + }; + if (reducedMotion()) { + finish(); + return; + } + panel.classList.add('faded'); + closeTimer = setTimeout(finish, FADE_MS); } async function send(kind: 'note' | 'bug') { if (busy || (kind === 'note' && !hasContent())) return; @@ -994,20 +1023,35 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s busy = true; update(); btn.text.textContent = 'Saving…'; + const icon = btn.el.firstElementChild; + const label = kind === 'bug' ? 'Bug' : 'Note'; try { await bridge('submit', { kind, text: text || null }); - ed.replaceChildren(); - savedRange = null; + // The session already cleared its copy; keep the sent text on screen only for the confirmation. + sealed = true; dirty = false; + panel.classList.add('sent'); + btn.text.textContent = 'Saved'; + icon?.replaceWith(svg(icons.check)); + status.textContent = `${label} saved`; + await wait(reducedMotion() ? 300 : 450); close(); - showToast(kind); + await wait(reducedMotion() ? 0 : FADE_MS + 10); + ed.replaceChildren(); + savedRange = null; + sealed = false; + saveDraftNow(); } catch (error) { showError( `Not saved: ${error instanceof Error ? error.message : String(error)} Your draft is kept.`, ); } finally { + sealed = false; busy = false; - btn.text.textContent = kind === 'bug' ? 'Bug' : 'Note'; + panel.classList.remove('sent'); + btn.text.textContent = label; + const current = btn.el.firstElementChild; + if (icon && current !== icon) current?.replaceWith(icon); update(); } } @@ -1028,7 +1072,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s } }); function flushSave() { - if (restoring) return; + if (restoring || sealed) return; cancelPendingSave(); const fn = w[bindingName]; if (typeof fn !== 'function') return; @@ -1061,6 +1105,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s await boot; if (!host.isConnected) document.documentElement.append(host); if (pointing) stopPoint(); + cancelClose(); const wasOpen = !panel.hidden; if (!wasOpen) { const draft = await loadAndApplyDraft(); @@ -1073,6 +1118,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s placeAt(draft.position); } keepInView(); + animateIn(); saveDraftNow(); } ed.focus({ preventScroll: true }); diff --git a/test/recorder.test.ts b/test/recorder.test.ts index 7bd2e1d..11af338 100644 --- a/test/recorder.test.ts +++ b/test/recorder.test.ts @@ -697,7 +697,8 @@ test('composer Esc close keeps draft hidden across reload until reopened', { await page.locator('terrific-composer .ed').click(); await page.keyboard.type('closed draft text'); await page.keyboard.press('Escape'); - equal(await page.locator('terrific-composer .panel').isVisible(), false); + // The panel fades out before it is hidden. + await page.locator('terrific-composer .panel').waitFor({ state: 'hidden' }); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('h1').waitFor(); From 858f01527613658b2248f66999b60215b90996ee Mon Sep 17 00:00:00 2001 From: Roderick Date: Sat, 7 Nov 2026 23:06:00 -0600 Subject: [PATCH 7/7] feat(recorder): point references, @ capture refs and chip copy and paste Pointed elements now serialize as the block from the markdown extension's Point to section, captured at pick time, without the page URL that navigation events already record. Screenshots serialize as @ss_.png and snapshots as @snapshot:. Copying from the note panel puts that text on the clipboard together with the full chip data, and pasting turns valid references back into chips. Inserting a capture or a pointed element no longer replaces selected text, and restoring a draft no longer adds a space after every chip. Co-Authored-By: Claude Opus 5.5 --- .agents/skills/terrific/SKILL.md | 2 +- .agents/skills/terrific/references/events.md | 8 +- src/recorder/composer-bridge.test.ts | 18 + src/recorder/composer-bridge.ts | 9 +- src/recorder/composer-script.ts | 580 ++++++++++++++++--- test/recorder.test.ts | 135 ++++- 6 files changed, 668 insertions(+), 84 deletions(-) diff --git a/.agents/skills/terrific/SKILL.md b/.agents/skills/terrific/SKILL.md index b0a2f0a..66c9c51 100644 --- a/.agents/skills/terrific/SKILL.md +++ b/.agents/skills/terrific/SKILL.md @@ -51,7 +51,7 @@ A validation that fails with no evident cause becomes a debug task, and its sess - If you can reproduce the bug yourself (a test, a script, `curl`), do it without asking the user. - Otherwise give the user short numbered steps and wait until they confirm they are done. Mention restarts only when the instrumentation needs one. - While the session runs, mark moments yourself with `terrific note|bug|flag [text]`. - - In a browser session, `terrific screenshot ` captures the page and `terrific snapshot ` saves it as markdown. Alt+right-click opens an in-page composer; chip tokens are under "Notes written in the browser" in [references/events.md](references/events.md). + - In a browser session, `terrific screenshot ` captures the page and `terrific snapshot ` saves it as markdown. Alt+right-click opens the Note panel; how to read its ``, `@ss_` and `@snapshot:` references is under "Notes written in the browser" in [references/events.md](references/events.md). - To watch live, run `terrific events --follow` in the background. It ends when the session stops. 7. Stop with `terrific stop `, which prints the summary and writes `context.txt` in the session folder. Omit the id when only one session is recording. - "Session is not recording" means the user already stopped it, so go straight to the evidence. diff --git a/.agents/skills/terrific/references/events.md b/.agents/skills/terrific/references/events.md index 0bb0aea..c6d923f 100644 --- a/.agents/skills/terrific/references/events.md +++ b/.agents/skills/terrific/references/events.md @@ -54,8 +54,10 @@ In any browser Terrific records, hold Alt and right-click to open the Note panel Note panel notes and bugs are stored as normal `note` / `bug` events with `author: 'tester'`. Chips serialize into the event text as: -- `[element SELECTOR "NAME"]` (name optional): use the CSS selector to locate the element in the page or app code. -- `[screenshot screenshots/ss_.png]`: path relative to the session folder; open that file under `screenshots/`. -- `[snapshot ev_]`: id of the `snapshot` event in `events.jsonl` (or `[snapshot]` when no id was available). Read with `terrific events --type snapshot --json` and match the record whose `id` is that `ev_`. +- A `` block on its own lines for each pointed element, captured when it was picked. It lists `Selector` (unique CSS selector; shadow roots are joined with ` >>> `), `Element`, and when present `Classes`, `Data attributes`, `Location` (landmark path), `Heading`, `Role`, `Accessible name`, `ARIA state`, `Text anchor`, siblings, `Children`, `Box` (size and page position, plus the viewport), `Positioning`, `Styles` and `Shadow DOM`. It describes where the element is, not its content. The page URL is not repeated: take it from the nearest `navigation` event before the note. +- `@ss_.png`: a screenshot; open `screenshots/ss_.png` in the session folder. +- `@snapshot:ev_`: the id of a `snapshot` event (or `@snapshot` when no id was available). Read with `terrific events --type snapshot --json` and match the record whose `id` is that `ev_`. + +Captures happen when the tester presses Screenshot or Snapshot, so each one is also its own event in the timeline, and a capture may exist that no note references. Copying from the panel puts this same text on the clipboard, and pasting it back turns valid references into chips again. Limitations: the draft (unsent text and chips) lives in memory for the whole session, survives reloads, navigation and new tabs, and is discarded when the session stops; nothing is written to disk until it is sent. Screenshot previews can be blocked by a page's image CSP (the chip still works); iframes and closed shadow roots cannot be pointed into from the top frame. diff --git a/src/recorder/composer-bridge.test.ts b/src/recorder/composer-bridge.test.ts index 2357b5a..c46eaad 100644 --- a/src/recorder/composer-bridge.test.ts +++ b/src/recorder/composer-bridge.test.ts @@ -452,3 +452,21 @@ test('handleComposerRequest clears draft only after successful submit', async () ); deepEqual(failed, []); }); + +test('parseComposerDraft keeps an element reference and rejects an oversized one', () => { + const reference = + '\n- Selector: `#email`\n- Element: ``\n'; + const element = { type: 'element', selector: '#email', name: 'Email', tag: 'input' }; + const base = { open: true, position: null, moved: false }; + const parsed = parseComposerDraft({ ...base, segments: [{ ...element, reference }] }); + deepEqual(parsed.segments[0], { ...element, reference }); + const withoutReference = parseComposerDraft({ ...base, segments: [element] }); + deepEqual(withoutReference.segments[0], element); + let error: unknown; + try { + parseComposerDraft({ ...base, segments: [{ ...element, reference: 'x'.repeat(8_001) }] }); + } catch (caught) { + error = caught; + } + equal(error instanceof Error ? error.message : '', 'Unsupported composer request.'); +}); diff --git a/src/recorder/composer-bridge.ts b/src/recorder/composer-bridge.ts index 0b09312..ae823b4 100644 --- a/src/recorder/composer-bridge.ts +++ b/src/recorder/composer-bridge.ts @@ -20,7 +20,7 @@ export type ComposerSubmitResult = { export type ComposerSegment = | { type: 'text'; text: string } - | { type: 'element'; selector: string; name: string; tag: string } + | { type: 'element'; selector: string; name: string; tag: string; reference?: string } | { type: 'screenshot'; label: string; file: string; width: number; height: number } | { type: 'snapshot'; @@ -61,6 +61,7 @@ export type ComposerBridgeDeps = { const MAX_TEXT = 20_000; const MAX_SEGMENTS = 200; const MAX_STRING = 2_000; +const MAX_REFERENCE = 8_000; const FILE_RE = /^screenshots\/ss_[A-Za-z0-9_-]+\.png$/; const TAG_RE = /^[a-z][a-z0-9-]*$/; @@ -92,12 +93,16 @@ function parseSegment(value: unknown): ComposerSegment { if (type === 'element') { const tag = requireString(value.tag); if (!TAG_RE.test(tag)) unsupported(); - return { + const segment: ComposerSegment = { type: 'element', selector: requireString(value.selector), name: requireString(value.name), tag, }; + // The block the page captured when the element was picked. + if (value.reference !== undefined) + segment.reference = requireString(value.reference, MAX_REFERENCE); + return segment; } if (type === 'screenshot') { const file = requireString(value.file); diff --git a/src/recorder/composer-script.ts b/src/recorder/composer-script.ts index 0a5f6a0..8a6a8ef 100644 --- a/src/recorder/composer-script.ts +++ b/src/recorder/composer-script.ts @@ -222,7 +222,14 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s layer.append(ref, hl, panel, pop, status); root.append(layer); type Chip = - | { kind: 'element'; el: Element | null; selector: string; name: string; tag: string } + | { + kind: 'element'; + el: Element | null; + selector: string; + name: string; + tag: string; + reference: string; + } | { kind: 'screenshot'; label: string; @@ -241,7 +248,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s }; type DraftSegment = | { type: 'text'; text: string } - | { type: 'element'; selector: string; name: string; tag: string } + | { type: 'element'; selector: string; name: string; tag: string; reference?: string } | { type: 'screenshot'; label: string; file: string; width: number; height: number } | { type: 'snapshot'; @@ -300,27 +307,248 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s const isOurs = (e: Event) => e.composedPath().includes(host); const usable = (el: Element | null): el is Element => !!el && el !== document.documentElement && el !== document.body && el !== host; - function selectorFor(el: Element) { + // Point reference, ported from terrific-markdown-extension contextTracker.js (Point to section). + // The page URL is left out because the session already records it as navigation events. + const visibleText = (el: Element) => + // biome-ignore lint/performance/useDomNodeTextContent: references describe the text the tester sees. + el instanceof HTMLElement ? el.innerText : el.textContent || ''; + const collapse = (value: unknown, max: number) => { + const text = String(value || '') + .replace(/\s+/g, ' ') + .trim(); + return text.length > max ? `${text.slice(0, max - 1)}…` : text; + }; + const inlineCode = (value: string) => `\`${String(value).replace(/`/g, "'")}\``; + const cssEscape = (value: string) => + typeof CSS !== 'undefined' && typeof CSS.escape === 'function' + ? CSS.escape(value) + : String(value).replace(/[^a-zA-Z0-9_-]/g, '\\$&'); + const cssEscapeAttr = (value: string) => + String(value).replace(/\\/g, '\\\\').replace(/"/g, '\\"'); + function composedParent(el: Element): Element | null { + if (el.parentElement) return el.parentElement; + const scope = el.getRootNode(); + return scope instanceof ShadowRoot ? scope.host : null; + } + function describeElement(el: Element) { + let label = el.localName; + const id = el.getAttribute('id'); + if (id) label += `#${id}`; + else { + const firstClass = (el.getAttribute('class') || '').trim().split(/\s+/)[0]; + if (firstClass) label += `.${firstClass}`; + } + return label.length > 36 ? `${label.slice(0, 35)}…` : label; + } + function selectorPart(el: Element) { + for (const attr of ['data-testid', 'data-test', 'name', 'aria-label', 'role']) { + const value = el.getAttribute(attr); + if (value) return `${el.localName}[${attr}="${cssEscapeAttr(value)}"]`; + } + const parent = el.parentElement; + if (!parent) return el.localName; + const same = Array.from(parent.children).filter((c) => c.localName === el.localName); + return same.length <= 1 ? el.localName : `${el.localName}:nth-of-type(${same.indexOf(el) + 1})`; + } + function selectorInScope(el: Element) { + const scope = el.getRootNode() as Document | ShadowRoot; + const unique = (selector: string) => { + try { + return scope.querySelectorAll(selector).length === 1; + } catch { + return false; + } + }; const parts: string[] = []; + for (let n: Element | null = el; n; n = n.parentElement) { + const id = n.getAttribute('id'); + if (id && unique(`#${cssEscape(id)}`)) { + parts.unshift(`#${cssEscape(id)}`); + return parts.join(' > '); + } + parts.unshift(selectorPart(n)); + const selector = parts.join(' > '); + if (unique(selector)) return selector; + if (n === document.documentElement) break; + } + return parts.join(' > '); + } + // Selector without a depth cap; shadow roots are joined with " >>> ". + function pointSelector(el: Element) { + const segments: string[] = []; + for (let n: Element | null = el; n; ) { + segments.unshift(selectorInScope(n)); + const scope = n.getRootNode(); + n = scope instanceof ShadowRoot ? scope.host : null; + } + return segments.join(' >>> '); + } + const LANDMARK_TAGS = new Set([ + 'main', + 'nav', + 'header', + 'footer', + 'aside', + 'section', + 'article', + 'form', + 'dialog', + ]); + const LANDMARK_ROLES = new Set([ + 'main', + 'navigation', + 'banner', + 'contentinfo', + 'complementary', + 'region', + 'article', + 'form', + 'search', + 'dialog', + 'alertdialog', + 'tabpanel', + 'list', + 'table', + 'grid', + ]); + function ariaName(el: Element) { + const label = el.getAttribute('aria-label'); + if (label) return collapse(label, 60); + const labelledBy = el.getAttribute('aria-labelledby'); + if (labelledBy) { + const scope = el.getRootNode() as Document | ShadowRoot; + const text = labelledBy + .split(/\s+/) + .map((id) => scope.getElementById?.(id)?.textContent || '') + .join(' '); + if (text.trim()) return collapse(text, 60); + } + return ''; + } + function headingText(el: Element) { + const heading = el.querySelector('h1, h2, h3, h4, h5, h6, [role="heading"]'); + return heading ? collapse(heading.textContent, 48) : ''; + } + function landmarkPath(el: Element) { + const labels: string[] = []; for ( let n: Element | null = el; - n && n !== document.body && parts.length < 4; - n = n.parentElement + n && n !== document.body && n !== document.documentElement; + n = composedParent(n) ) { - if (n.id) { - parts.unshift( - `${n.localName}#${typeof window.CSS === 'undefined' ? n.id : CSS.escape(n.id)}`, - ); - break; - } - let part = n.localName; - const siblings = n.parentElement - ? Array.from(n.parentElement.children).filter((c) => c.localName === n?.localName) - : []; - if (siblings.length > 1) part += `:nth-of-type(${siblings.indexOf(n) + 1})`; - parts.unshift(part); + const role = n.getAttribute('role') || ''; + if (!LANDMARK_TAGS.has(n.localName) && !LANDMARK_ROLES.has(role)) continue; + const name = ariaName(n) || (n === el ? '' : headingText(n)); + labels.unshift(name ? `${role || n.localName} "${name}"` : role || n.localName); } - return parts.join(' > '); + return labels.join(' > '); + } + function nearestHeading(el: Element) { + const inside = headingText(el); + if (inside) return { text: inside, relation: 'inside' }; + let found: Element | null = null; + for (const heading of document.querySelectorAll('h1, h2, h3, h4, h5, h6, [role="heading"]')) { + if (heading.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING) found = heading; + } + return found ? { text: collapse(found.textContent, 48), relation: 'before' } : null; + } + function fixedOrSticky(el: Element) { + for (let n: Element | null = el; n; n = composedParent(n)) { + const position = getComputedStyle(n).position; + if (position === 'fixed' || position === 'sticky') return position; + } + return ''; + } + const POINT_STYLE_PROPS: [string, string[]][] = [ + ['display', ['inline', 'none']], + ['position', ['static']], + ['z-index', ['auto']], + ['overflow', ['visible']], + ['font-size', []], + ['font-weight', ['400']], + ['color', []], + ['background-color', ['rgba(0, 0, 0, 0)', 'transparent']], + ['padding', ['0px']], + ['margin', ['0px']], + ['border-radius', ['0px']], + ]; + function pointStyles(el: Element) { + const style = getComputedStyle(el); + const entries: string[] = []; + for (const [prop, skip] of POINT_STYLE_PROPS) { + const value = style.getPropertyValue(prop).trim(); + if (value && !skip.includes(value)) entries.push(`${prop}: ${value}`); + } + return entries.join('; '); + } + function describeNeighbor(el: Element | null) { + if (!el) return ''; + const text = collapse(visibleText(el), 40); + return text ? `${inlineCode(describeElement(el))} "${text}"` : inlineCode(describeElement(el)); + } + // Describes where an element is, never what it contains beyond a short locating anchor. + function pointReference(el: Element) { + const rect = el.getBoundingClientRect(); + const lines: string[] = []; + const add = (label: string, value: string | false | null | undefined | 0) => { + if (value) lines.push(`- ${label}: ${value}`); + }; + const classes = collapse(el.getAttribute('class'), 160); + const attrs: string[] = []; + for (const attr of Array.from(el.attributes)) { + if (!/^data-/.test(attr.name) || attr.name.startsWith('data-terrific')) continue; + if (attrs.length >= 6) break; + attrs.push(`${attr.name}="${collapse(attr.value, 60)}"`); + } + const ariaStates = [ + 'aria-expanded', + 'aria-selected', + 'aria-checked', + 'aria-pressed', + 'aria-current', + 'aria-disabled', + 'aria-hidden', + ] + .map((name) => (el.hasAttribute(name) ? `${name}="${el.getAttribute(name)}"` : '')) + .filter(Boolean); + const heading = nearestHeading(el); + const textAnchor = collapse(visibleText(el), 100); + const name = ariaName(el); + const role = el.getAttribute('role'); + const styles = pointStyles(el); + add('Selector', inlineCode(pointSelector(el))); + add('Element', inlineCode(`<${el.localName}${el.id ? ` id="${el.id}"` : ''}>`)); + add('Classes', classes && inlineCode(classes)); + add('Data attributes', attrs.length && inlineCode(attrs.join(' '))); + add('Location', landmarkPath(el)); + add('Heading', heading && `"${heading.text}" (${heading.relation})`); + add('Role', role && inlineCode(role)); + add('Accessible name', name && `"${name}"`); + add('ARIA state', ariaStates.length && inlineCode(ariaStates.join(' '))); + add('Text anchor', textAnchor && `"${textAnchor}"`); + add('Previous sibling', describeNeighbor(el.previousElementSibling)); + add('Next sibling', describeNeighbor(el.nextElementSibling)); + add('Children', el.children.length ? String(el.children.length) : ''); + add( + 'Box', + `${Math.round(rect.width)}×${Math.round(rect.height)} at page (${Math.round(rect.left + window.scrollX)}, ${Math.round(rect.top + window.scrollY)}), viewport ${window.innerWidth}×${window.innerHeight}`, + ); + add('Positioning', fixedOrSticky(el)); + add('Styles', styles && inlineCode(styles)); + add( + 'Shadow DOM', + el.getRootNode() instanceof ShadowRoot ? 'yes, selector pierces with `>>>`' : '', + ); + return ['', ...lines, ''].join('\n'); + } + // Minimal reference for element chips restored without one (drafts from before references existed). + function fallbackReference(selector: string, tag: string) { + return [ + '', + `- Selector: ${inlineCode(selector)}`, + `- Element: ${inlineCode(`<${tag}>`)}`, + '', + ].join('\n'); } function accessibleName(el: Element) { const labelled = 'labels' in el ? (el as HTMLInputElement).labels?.[0] : null; @@ -383,7 +611,17 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s } function resolveElement(selector: string): Element | null { try { - const found = document.querySelector(selector); + const parts = selector.split(' >>> '); + let scope: Document | ShadowRoot = document; + let found: Element | null = null; + for (let i = 0; i < parts.length; i++) { + found = scope.querySelector(parts[i] ?? ''); + if (!found) return null; + if (i < parts.length - 1) { + if (!found.shadowRoot) return null; + scope = found.shadowRoot; + } + } if (!found || found === host || host.contains(found)) return null; return found; } catch { @@ -403,7 +641,8 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s function insertChip(chip: HTMLElement) { ed.focus({ preventScroll: true }); const r = rangeInEditor(); - r.deleteContents(); + // Insert after any selected text instead of replacing it. + r.collapse(false); const after = document.createTextNode(' '), frag = document.createDocumentFragment(); if (needsLeadingSpace(r)) frag.append(' '); @@ -435,9 +674,16 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s } function addElement(el: Element | null) { if (!usable(el)) return; - const selector = selectorFor(el); const chip = makeChip( - { kind: 'element', el, selector, name: accessibleName(el), tag: el.localName }, + { + kind: 'element', + el, + selector: pointSelector(el), + name: accessibleName(el), + tag: el.localName, + // Captured at pick time so the box and styles describe what the tester saw. + reference: pointReference(el), + }, `<${el.localName}>`, ); insertChip(chip); @@ -453,9 +699,42 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s dirty = true; scheduleSave(); }); + // Copy and cut put two formats on the clipboard: the text form (pointed-section, @ss_, @snapshot:) + // for pasting anywhere, and the full segments so pasting back into a panel restores identical chips. + function copySelection(e: ClipboardEvent, cut: boolean) { + const s = selection(); + if (!s?.rangeCount || !e.clipboardData) return; + const range = s.getRangeAt(0); + if (range.collapsed || !ed.contains(range.commonAncestorContainer)) return; + const segments = buildSegments(range); + e.preventDefault(); + e.clipboardData.setData('text/plain', serializeSegments(segments)); + e.clipboardData.setData(SEGMENTS_MIME, JSON.stringify(segments)); + if (cut) document.execCommand('delete'); + } + ed.addEventListener('copy', (e) => copySelection(e, false)); + ed.addEventListener('cut', (e) => copySelection(e, true)); ed.addEventListener('paste', (e) => { e.preventDefault(); - document.execCommand('insertText', false, e.clipboardData?.getData('text/plain') || ''); + const data = e.clipboardData; + if (!data) return; + let segments: DraftSegment[] | null = null; + const rich = data.getData(SEGMENTS_MIME); + if (rich) { + try { + segments = cleanSegments(JSON.parse(rich)); + } catch { + segments = null; + } + } + const text = data.getData('text/plain') || ''; + segments ??= parseTokens(text); + if (segments.every((s) => s.type === 'text')) { + // Plain text keeps the browser's own insertion, including undo. + document.execCommand('insertText', false, text); + return; + } + insertSegments(segments); }); ed.addEventListener('keydown', (e) => { if (e.key === 'Enter' && !e.ctrlKey && !e.metaKey && !e.shiftKey) { @@ -660,13 +939,15 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s img.addEventListener('error', () => container.remove()); pop.append(container); } + const fileName = data.file.replace(/^screenshots\//, ''); pop.append( h('div', { class: 'meta' }, [ h('b', {}, [data.label]), - h('span', {}, [`${data.width}×${data.height}`]), + // Pasted chips only know the file, not the capture size. + h('span', {}, [data.width > 0 ? `${data.width}×${data.height}` : fileName]), ]), ); - } else { + } else if (data.title) { pop.append( h('div', { class: 'sn' }, [ h('b', {}, [`${data.label} · page scrape`]), @@ -674,6 +955,13 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s h('div', { class: 'excerpt' }, [`${data.excerpt}…`]), ]), ); + } else { + pop.append( + h('div', { class: 'sn' }, [ + h('b', {}, [`${data.label} · page scrape`]), + h('span', {}, [data.id ?? '']), + ]), + ); } pop.hidden = false; const cr = chip.getBoundingClientRect(), @@ -775,18 +1063,139 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s snap.el.addEventListener('click', () => { void capture('snapshot'); }); - function serialize(node: Node = ed): string { + // Text form of a draft, used for the stored note and for the clipboard: + // elements as a block, screenshots as @ss_.png, snapshots as @snapshot:. + function segmentText(segment: DraftSegment): string { + if (segment.type === 'text') return segment.text; + if (segment.type === 'element') { + return segment.reference || fallbackReference(segment.selector, segment.tag); + } + if (segment.type === 'screenshot') return `@${segment.file.replace(/^screenshots\//, '')}`; + return segment.id ? `@snapshot:${segment.id}` : '@snapshot'; + } + // Element blocks sit on their own lines; a line break is added only where the text lacks one. + function serializeSegments(segments: DraftSegment[]): string { let out = ''; - for (const n of node.childNodes) { - if (n.nodeType === Node.TEXT_NODE) out += (n as Text).data; - else if (n.nodeName === 'BR') out += '\n'; - else if (n instanceof Element && n.classList.contains('ch')) { - const d = chipData.get(n); - if (!d) continue; - if (d.kind === 'element') out += `[element ${d.selector}${d.name ? ` "${d.name}"` : ''}]`; - else if (d.kind === 'screenshot') out += `[screenshot ${d.file}]`; - else out += d.id ? `[snapshot ${d.id}]` : '[snapshot]'; - } else out += (n.nodeName === 'DIV' && out && !out.endsWith('\n') ? '\n' : '') + serialize(n); + let afterBlock = false; + for (const segment of segments) { + let piece = segmentText(segment); + if (segment.type === 'element') { + out = out.replace(/[ \t]+$/, ''); + if (out && !out.endsWith('\n')) out += '\n'; + out += piece; + afterBlock = true; + continue; + } + if (afterBlock) { + piece = piece.replace(/^[ \t]+/, ''); + if (!piece) continue; + if (!piece.startsWith('\n')) piece = `\n${piece}`; + afterBlock = false; + } + out += piece; + } + return out.replace(/[ \t]+\n/g, '\n').trim(); + } + const SEGMENTS_MIME = 'application/x-terrific-segments+json'; + const TOKEN_RE = + /(?:]*>\s*)?([\s\S]*?)<\/pointed-section>(?:\s*<\/page-reference>)?|@ss_[A-Za-z0-9_-]+\.png|@snapshot:ev_[A-Za-z0-9_-]+/g; + // Turns one pasted token into a chip segment; anything malformed stays plain text. + function tokenSegment(token: string, body: string | undefined): DraftSegment | null { + if (body !== undefined) { + const selector = /^- Selector: `([^`]+)`/m.exec(body)?.[1]; + const tag = /^- Element: `<([a-z][a-z0-9-]*)/m.exec(body)?.[1]; + const reference = `${body}`; + if (!selector || !tag || selector.length > 2000 || reference.length > 8000) return null; + const name = + /^- Accessible name: "(.*)"$/m.exec(body)?.[1] || + /^- Heading: "(.*)" \(/m.exec(body)?.[1] || + ''; + return { type: 'element', selector, tag, name: name.slice(0, 40), reference }; + } + if (token.startsWith('@ss_')) { + return { + type: 'screenshot', + label: 'Screenshot', + file: `screenshots/${token.slice(1)}`, + width: 0, + height: 0, + }; + } + const id = token.slice('@snapshot:'.length); + return { type: 'snapshot', label: 'Snapshot', id, title: '', wordCount: 0, excerpt: '' }; + } + function parseTokens(text: string): DraftSegment[] { + const segments: DraftSegment[] = []; + let last = 0; + for (const match of text.matchAll(TOKEN_RE)) { + const segment = tokenSegment(match[0], match[1]); + if (!segment) continue; + const index = match.index ?? 0; + if (index > last) segments.push({ type: 'text', text: text.slice(last, index) }); + segments.push(segment); + last = index + match[0].length; + } + if (last < text.length) segments.push({ type: 'text', text: text.slice(last) }); + return segments; + } + // Re-validates segments read from the clipboard; returns null if anything does not fit the draft model. + function cleanSegments(value: unknown): DraftSegment[] | null { + if (!Array.isArray(value) || value.length > 200) return null; + const str = (v: unknown, max = 2000) => typeof v === 'string' && v.length <= max; + const num = (v: unknown) => typeof v === 'number' && Number.isFinite(v); + const out: DraftSegment[] = []; + for (const s of value) { + if (!s || typeof s !== 'object') return null; + const v = s as Record; + if (v.type === 'text' && str(v.text, 20000)) + out.push({ type: 'text', text: v.text as string }); + else if ( + v.type === 'element' && + str(v.selector) && + str(v.name) && + typeof v.tag === 'string' && + /^[a-z][a-z0-9-]*$/.test(v.tag) && + (v.reference === undefined || str(v.reference, 8000)) + ) + out.push({ + type: 'element', + selector: v.selector as string, + name: v.name as string, + tag: v.tag, + reference: v.reference as string | undefined, + }); + else if ( + v.type === 'screenshot' && + str(v.label) && + typeof v.file === 'string' && + /^screenshots\/ss_[A-Za-z0-9_-]+\.png$/.test(v.file) && + num(v.width) && + num(v.height) + ) + out.push({ + type: 'screenshot', + label: v.label as string, + file: v.file, + width: v.width as number, + height: v.height as number, + }); + else if ( + v.type === 'snapshot' && + str(v.label) && + (v.id === null || str(v.id)) && + str(v.title) && + num(v.wordCount) && + str(v.excerpt) + ) + out.push({ + type: 'snapshot', + label: v.label as string, + id: v.id as string | null, + title: v.title as string, + wordCount: v.wordCount as number, + excerpt: v.excerpt as string, + }); + else return null; } return out; } @@ -806,7 +1215,8 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s if (!Number.isFinite(leftN) || !Number.isFinite(topN)) return null; return { left: leftN, top: topN }; } - function buildSegments(): DraftSegment[] { + // Segments of the whole editor, or only of the part inside `range` (for copy and cut). + function buildSegments(range?: Range): DraftSegment[] { const segments: DraftSegment[] = []; let text = ''; const flush = () => { @@ -814,10 +1224,17 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s segments.push({ type: 'text', text }); text = ''; }; + const outside = (n: Node) => range !== undefined && !range.intersectsNode(n); const walk = (node: Node) => { for (const n of node.childNodes) { + if (outside(n)) continue; if (n.nodeType === Node.TEXT_NODE) { - text += (n as Text).data; + let data = (n as Text).data; + if (range) { + const end = n === range.endContainer ? range.endOffset : data.length; + data = data.slice(n === range.startContainer ? range.startOffset : 0, end); + } + text += data; continue; } if (n.nodeName === 'BR') { @@ -834,6 +1251,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s selector: d.selector, name: d.name, tag: d.tag, + reference: d.reference, }); } else if (d.kind === 'screenshot') { segments.push({ @@ -905,38 +1323,34 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s } keepInView(); } - function appendTextSegment(value: string) { - const parts = value.split('\n'); - for (let i = 0; i < parts.length; i++) { - if (i > 0) ed.append(document.createElement('br')); - const part = parts[i]; - if (part) ed.append(part); + // DOM nodes for one segment. Spacing lives in the text segments, so nothing is added around chips. + function segmentNodes(segment: DraftSegment & { preview?: string | null }): Node[] { + if (segment.type === 'text') { + const nodes: Node[] = []; + segment.text.split('\n').forEach((part, i) => { + if (i > 0) nodes.push(document.createElement('br')); + if (part) nodes.push(document.createTextNode(part)); + }); + return nodes; } - } - function applyDraft(draft: DraftWithPreviews) { - ed.replaceChildren(); - savedRange = null; - for (const segment of draft.segments) { - if (segment.type === 'text') { - appendTextSegment(segment.text); - continue; - } - if (segment.type === 'element') { - const chip = makeChip( + if (segment.type === 'element') { + return [ + makeChip( { kind: 'element', el: null, selector: segment.selector, name: segment.name, tag: segment.tag, + reference: segment.reference || fallbackReference(segment.selector, segment.tag), }, `<${segment.tag}>`, - ); - ed.append(chip, document.createTextNode(' ')); - continue; - } - if (segment.type === 'screenshot') { - const chip = makeChip( + ), + ]; + } + if (segment.type === 'screenshot') { + return [ + makeChip( { kind: 'screenshot', label: segment.label, @@ -947,11 +1361,11 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s }, segment.label, icons.cam, - ); - ed.append(chip, document.createTextNode(' ')); - continue; - } - const chip = makeChip( + ), + ]; + } + return [ + makeChip( { kind: 'snapshot', label: segment.label, @@ -962,12 +1376,35 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s }, segment.label, icons.scan, - ); - ed.append(chip, document.createTextNode(' ')); - } + ), + ]; + } + function applyDraft(draft: DraftWithPreviews) { + ed.replaceChildren(...draft.segments.flatMap(segmentNodes)); + savedRange = null; moved = draft.moved; update(); } + // Pasted segments replace the selection, like any paste. + function insertSegments(segments: DraftSegment[]) { + ed.focus({ preventScroll: true }); + const r = rangeInEditor(); + r.deleteContents(); + const nodes = segments.flatMap(segmentNodes); + const lastNode = nodes[nodes.length - 1]; + if (!lastNode) return; + const frag = document.createDocumentFragment(); + frag.append(...nodes); + r.insertNode(frag); + const caret = document.createRange(); + caret.setStartAfter(lastNode); + caret.collapse(true); + placeCaret(caret); + hideError(); + update(); + dirty = true; + saveDraftNow(); + } async function loadAndApplyDraft(): Promise { if (dirty) return null; const fn = w[bindingName]; @@ -1016,10 +1453,7 @@ kbd{font:500 10px "JetBrains Mono",Consolas,monospace;color:#71717a;border:1px s hidePreview(); cancelPendingSave(); const btn = kind === 'bug' ? bug : note; - const text = serialize() - .replace(/[ \t]+\n/g, '\n') - .replace(/\s+$/, '') - .replace(/^\s+/, ''); + const text = serializeSegments(buildSegments()); busy = true; update(); btn.text.textContent = 'Saving…'; diff --git a/test/recorder.test.ts b/test/recorder.test.ts index 11af338..3b5edc6 100644 --- a/test/recorder.test.ts +++ b/test/recorder.test.ts @@ -388,7 +388,7 @@ test('composer Point tool submits a note without recording composer actions', { equal(notes.length, 1); if (notes[0]?.kind === 'note') { equal(notes[0].author, 'tester'); - match(notes[0].text, /\[element /); + match(notes[0].text, /\n- Selector: `[^`]+`\n- Element: `<[a-z]/); match(notes[0].text, /typed note body/); } const actionsAfter = collected.events.filter((event) => event.kind === 'action').length; @@ -441,8 +441,8 @@ test('composer Screenshot and Snapshot tools append captures and store a bug wit equal(bugs.length, 1); if (bugs[0]?.kind === 'bug') { equal(bugs[0].author, 'tester'); - match(bugs[0].text ?? '', /\[screenshot screenshots\/ss_/); - match(bugs[0].text ?? '', /\[snapshot ev_test_/); + match(bugs[0].text ?? '', /@ss_[A-Za-z0-9_-]+\.png/); + match(bugs[0].text ?? '', /@snapshot:ev_test_/); } } finally { await recording.stop(); @@ -554,6 +554,7 @@ test('composer draft survives reload with chips and without stealing focus', { await page.locator('#email').click(); await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + await page.locator('terrific-composer .ch.cap').waitFor(); equal(await page.locator('terrific-composer .ch.el').count(), 1); equal(await page.locator('terrific-composer .ch.cap').count(), 1); @@ -604,6 +605,7 @@ test('composer draft survives navigation and marks missing element chips gone', await page.locator('#email').click(); await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + await page.locator('terrific-composer .ch.cap').waitFor(); await page.goto(`${site.url}/page2.html`, { waitUntil: 'domcontentloaded' }); await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); @@ -646,6 +648,8 @@ test('composer submit after reload clears the draft for the next open', { await page.locator('#email').click(); await page.locator('terrific-composer .tl', { hasText: 'Screenshot' }).click(); await waitFor(collected.events, (seen) => seen.some((event) => event.kind === 'screenshot')); + // The event lands before the page receives the result; reload only once the chip exists. + await page.locator('terrific-composer .ch.cap').waitFor(); await page.reload({ waitUntil: 'domcontentloaded' }); await page.locator('terrific-composer .panel').waitFor({ state: 'visible' }); @@ -656,8 +660,8 @@ test('composer submit after reload clears the draft for the next open', { equal(notes.length, 1); if (notes[0]?.kind === 'note') { match(notes[0].text, /submit after reload/); - match(notes[0].text, /\[element /); - match(notes[0].text, /\[screenshot screenshots\/ss_/); + match(notes[0].text, /\n- Selector: `[^`]+`\n- Element: `<[a-z]/); + match(notes[0].text, /@ss_[A-Za-z0-9_-]+\.png/); } await page.reload({ waitUntil: 'domcontentloaded' }); @@ -759,3 +763,124 @@ test('composer screenshot labels continue across reload', { await site.close(); } }); + +test('composer inserts a capture after selected text instead of replacing it', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .ed').click(); + await page.keyboard.type('keep this text'); + await page.keyboard.press('Control+A'); + await page.locator('terrific-composer .tl', { hasText: 'Snapshot' }).click(); + await page.locator('terrific-composer .ch').waitFor(); + match((await page.locator('terrific-composer .ed').textContent()) ?? '', /keep this text/); + equal(await page.locator('terrific-composer .ch').count(), 1); + } finally { + await recording.stop(); + await site.close(); + } +}); + +test('composer copies chips as references and pastes them back as chips', { + timeout: 60_000, +}, async (t) => { + const browser = firstBrowser(t); + if (browser === undefined) return; + + const site = await serveSite(); + const screenshotsDir = await mkdtemp(join(tmpdir(), 'terrific-shots-')); + tempDirs.push(screenshotsDir); + const collected = collectEvents(); + const recording = await startRecording({ + browser: { executablePath: browser.executablePath, userDataDir: null, headless: true }, + url: `${site.url}/`, + record: { actions: false, network: false, console: false }, + screenshotsDir, + random: (n) => randomBytes(n), + onEvent: collected.onEvent, + appendEvent: collected.appendEvent, + }); + try { + const page = recording.page; + await openComposer(page); + await page.locator('terrific-composer .tl', { hasText: 'Point' }).click(); + await page.locator('#email').click(); + await page.keyboard.type('after'); + await page.keyboard.press('Control+A'); + + const copied = await page.evaluate(() => { + const ed = document.querySelector('terrific-composer')?.shadowRoot?.querySelector('.ed'); + const data = new DataTransfer(); + ed?.dispatchEvent( + new ClipboardEvent('copy', { clipboardData: data, bubbles: true, cancelable: true }), + ); + return { + text: data.getData('text/plain'), + rich: data.getData('application/x-terrific-segments+json'), + }; + }); + match(copied.text, /^\n- Selector: `#email`\n- Element: ``/); + match(copied.text, /<\/pointed-section>\nafter$/); + const rich = JSON.parse(copied.rich) as { type: string; reference?: string }[]; + equal(rich[0]?.type, 'element'); + match(rich[0]?.reference ?? '', /^/); + + const paste = (text: string, richData?: string) => + page.evaluate( + ([plain, segments]) => { + const ed = document.querySelector('terrific-composer')?.shadowRoot?.querySelector('.ed'); + const data = new DataTransfer(); + data.setData('text/plain', plain ?? ''); + if (segments) data.setData('application/x-terrific-segments+json', segments); + ed?.dispatchEvent( + new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }), + ); + }, + [text, richData] as const, + ); + + // Rich paste restores the identical element chip. + await page.keyboard.press('Control+A'); + await page.keyboard.press('Delete'); + await paste(copied.text, copied.rich); + equal(await page.locator('terrific-composer .ch.el').count(), 1); + + // Plain text tokens become chips; malformed tokens stay text. + await page.keyboard.press('Control+A'); + await page.keyboard.press('Delete'); + await paste( + 'see\n\n- Selector: `#color`\n- Element: `