Skip to content

The agent that grows with you

fix(desktop): comment mode redacts the whole picked tree and keeps nested groups together

Adolanium7c15d6994de3
diff --git a/apps/desktop/src/lib/preview-annotate/group.test.ts b/apps/desktop/src/lib/preview-annotate/group.test.ts
index fa3d9dd417c..e6b51687f4b 100644
--- a/apps/desktop/src/lib/preview-annotate/group.test.ts
+++ b/apps/desktop/src/lib/preview-annotate/group.test.ts
@@ -106,6 +106,43 @@ describe('groupAnnotations', () => {
expect(groups).toHaveLength(1)
expect(groups[0]?.items).toHaveLength(2)
})
+
+ it('merges a container comment with the comments nested inside it', () => {
+ const groups = groupAnnotations([
+ item(1, 'body>main'),
+ item(2, 'body>main>section.hero>h1'),
+ item(3, 'body>main>section.pricing>button'),
+ item(4, 'body>main>section.faq>li')
+ ])
+
+ expect(groups).toHaveLength(1)
+ expect(groups[0]?.items.map(entry => entry.number)).toEqual([1, 2, 3, 4])
+
+ const keys = groups.map(group => group.key)
+ const nested = keys.filter(key => keys.some(other => other !== key && other.startsWith(`${key}>`)))
+
+ expect(nested).toEqual([])
+ })
+
+ it('keeps a sibling region separate while merging a nested container', () => {
+ const groups = groupAnnotations([
+ item(1, 'body>header.nav>a.logo'),
+ item(2, 'body>header.nav>ul.links'),
+ item(3, 'body>main'),
+ item(4, 'body>main>section.hero>h1'),
+ item(5, 'body>main>section.pricing>button')
+ ])
+
+ expect(groups.map(group => group.label)).toEqual(['header.nav', 'main'])
+ expect(groups.map(group => group.key)).toEqual(['body>header.nav', 'body>main'])
+ expect(groups[0]?.items.map(entry => entry.number)).toEqual([1, 2])
+ expect(groups[1]?.items.map(entry => entry.number)).toEqual([3, 4, 5])
+
+ const keys = groups.map(group => group.key)
+ const nested = keys.filter(key => keys.some(other => other !== key && other.startsWith(`${key}>`)))
+
+ expect(nested).toEqual([])
+ })
})
describe('groupAnnotations refinement', () => {
diff --git a/apps/desktop/src/lib/preview-annotate/group.ts b/apps/desktop/src/lib/preview-annotate/group.ts
index 04b9e3f8025..1bedc5703e5 100644
--- a/apps/desktop/src/lib/preview-annotate/group.ts
+++ b/apps/desktop/src/lib/preview-annotate/group.ts
@@ -148,6 +148,87 @@ function refine(groups: AnnotateGroup[], total: number): AnnotateGroup[] {
return current
}
+/**
+ * A comment on a container plus comments inside it must stay one group.
+ * Nested keys would tell the model those pieces of work are safe to run in
+ * parallel, and they are not.
+ *
+ * Walk the clicked selectors, not the bucket keys. A comment on `main` can
+ * bucket as `body`, and that key is a prefix of `body>header.nav` even though
+ * header is a sibling. The element the user actually pointed at is what
+ * decides ownership. Empty-key unanchored comments never swallow a placed
+ * group.
+ */
+function flattenNested(groups: AnnotateGroup[]): AnnotateGroup[] {
+ const firstNumber = (group: AnnotateGroup) => group.items[0]?.number ?? 0
+ const selectorsOf = (group: AnnotateGroup) =>
+ group.items.map(item => item.identity?.selector || '').filter(Boolean)
+ const owns = (parent: AnnotateGroup, child: AnnotateGroup): boolean => {
+ const parents = selectorsOf(parent)
+ const children = selectorsOf(child)
+
+ if (!parents.length || !children.length) {
+ return false
+ }
+
+ return children.every(childSel =>
+ parents.some(parentSel => childSel === parentSel || childSel.startsWith(`${parentSel}>`))
+ )
+ }
+ const sorted = [...groups].sort((left, right) => {
+ const leftMin = Math.min(...selectorsOf(left).map(sel => sel.length))
+ const rightMin = Math.min(...selectorsOf(right).map(sel => sel.length))
+
+ if (leftMin !== rightMin) {
+ return leftMin - rightMin
+ }
+
+ return firstNumber(left) - firstNumber(right)
+ })
+ const kept: AnnotateGroup[] = []
+
+ for (const group of sorted) {
+ const parent = kept.find(candidate => candidate.key !== '' && owns(candidate, group))
+
+ if (parent) {
+ parent.items.push(...group.items)
+ parent.items.sort((left, right) => left.number - right.number)
+ const key = sharedSelectorPrefix(selectorsOf(parent))
+ parent.key = key
+ parent.label = labelFor(key)
+ continue
+ }
+
+ kept.push({ items: [...group.items], key: group.key, label: group.label })
+ }
+
+ kept.sort((left, right) => firstNumber(left) - firstNumber(right))
+
+ return kept
+}
+
+function sharedSelectorPrefix(selectors: string[]): string {
+ if (!selectors.length) {
+ return ''
+ }
+
+ const parts = selectors.map(segments)
+ const shortest = Math.min(...parts.map(list => list.length))
+ const common: string[] = []
+
+ for (let i = 0; i < shortest; i++) {
+ const seg = parts[0]?.[i]
+
+ if (!seg || parts.some(list => list[i] !== seg)) {
+ break
+ }
+
+ common.push(seg)
+ }
+
+ return common.join(SEP)
+}
+
/**
* Split a packed batch into groups the model can hand out in parallel.
*
@@ -160,7 +241,7 @@ export function groupAnnotations(items: readonly ComposerReadyAnnotation[]): Ann
const placed = items.filter(item => item.identity?.selector)
const loose = items.filter(item => !item.identity?.selector)
const depth = annotateSplitDepth(placed.map(item => item.identity?.selector || ''))
- const groups = refine(bucket(placed, depth), placed.length)
+ const groups = flattenNested(refine(bucket(placed, depth), placed.length))
if (loose.length) {
groups.push({ items: [...loose], key: '', label: '' })
diff --git a/apps/desktop/src/lib/preview-annotate/in-page.test.ts b/apps/desktop/src/lib/preview-annotate/in-page.test.ts
index 74828aeee98..691c846e5af 100644
--- a/apps/desktop/src/lib/preview-annotate/in-page.test.ts
+++ b/apps/desktop/src/lib/preview-annotate/in-page.test.ts
@@ -188,6 +188,128 @@ describe('annotateInPage overlay', () => {
api.teardown()
})
+ it('redacts secret attributes on descendants, not only on the picked node', async () => {
+ const section = document.createElement('section')
+ const child = document.createElement('button')
+ child.setAttribute('data-api-key', 'sk-live-nested')
+ child.textContent = 'Pay'
+ section.appendChild(child)
+ document.body.appendChild(section)
+ section.getBoundingClientRect = () => ({
+ bottom: 60,
+ height: 50,
+ left: 0,
+ right: 200,
+ toJSON: () => ({}),
+ top: 10,
+ width: 200,
+ x: 0,
+ y: 10
+ })
+ document.elementFromPoint = () => section
+
+ const api = annotateInPage(document)
+ api.install()
+ const pending = api.wait()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 20, clientY: 20 }))
+ host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 21, clientY: 21 }))
+
+ const event = await pending
+
+ expect(event.type).toBe('pick-element')
+
+ if (event.type === 'pick-element') {
+ expect(event.identity.html).not.toContain('sk-live-nested')
+ expect(event.identity.html).toContain('[redacted]')
+ expect(event.identity.html).toContain('Pay')
+ }
+
+ api.teardown()
+ })
+
+ it('redacts a typed password that never became a value attribute', async () => {
+ const wrap = document.createElement('div')
+ const input = document.createElement('input')
+ input.type = 'password'
+ input.value = 'typed-secret-999'
+ wrap.appendChild(input)
+ document.body.appendChild(wrap)
+ wrap.getBoundingClientRect = () => ({
+ bottom: 60,
+ height: 50,
+ left: 0,
+ right: 200,
+ toJSON: () => ({}),
+ top: 10,
+ width: 200,
+ x: 0,
+ y: 10
+ })
+ document.elementFromPoint = () => wrap
+
+ const api = annotateInPage(document)
+ api.install()
+ const pending = api.wait()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 20, clientY: 20 }))
+ host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 21, clientY: 21 }))
+
+ const event = await pending
+
+ expect(event.type).toBe('pick-element')
+
+ if (event.type === 'pick-element') {
+ expect(event.identity.html).not.toContain('typed-secret-999')
+ expect(event.identity.html).toContain('[redacted]')
+ }
+
+ api.teardown()
+ })
+
+ it('redacts a secret textarea body and does not leak it as Target text', async () => {
+ const form = document.createElement('form')
+ const area = document.createElement('textarea')
+ area.name = 'id_token'
+ area.value = 'BEGIN PRIVATE KEY'
+ form.appendChild(area)
+ document.body.appendChild(form)
+ form.getBoundingClientRect = () => ({
+ bottom: 60,
+ height: 50,
+ left: 0,
+ right: 200,
+ toJSON: () => ({}),
+ top: 10,
+ width: 200,
+ x: 0,
+ y: 10
+ })
+ document.elementFromPoint = () => form
+
+ const api = annotateInPage(document)
+ api.install()
+ const pending = api.wait()
+ const host = document.querySelector('hermes-annotate') as HTMLElement
+
+ host.dispatchEvent(new MouseEvent('mousedown', { bubbles: true, button: 0, clientX: 20, clientY: 20 }))
+ host.dispatchEvent(new MouseEvent('mouseup', { bubbles: true, button: 0, clientX: 21, clientY: 21 }))
+
+ const event = await pending
+
+ expect(event.type).toBe('pick-element')
+
+ if (event.type === 'pick-element') {
+ expect(event.identity.html).not.toContain('BEGIN PRIVATE KEY')
+ expect(event.identity.text).not.toContain('BEGIN PRIVATE KEY')
+ expect(event.identity.html).toContain('[redacted]')
+ }
+
+ api.teardown()
+ })
+
it('budgets the markup so one comment cannot paste a whole section', async () => {
const section = document.createElement('section')
section.innerHTML = '<p>filler filler filler</p>'.repeat(200)
diff --git a/apps/desktop/src/lib/preview-annotate/in-page.ts b/apps/desktop/src/lib/preview-annotate/in-page.ts
index 2de7bf5a0b5..c3fa9c7587e 100644
--- a/apps/desktop/src/lib/preview-annotate/in-page.ts
+++ b/apps/desktop/src/lib/preview-annotate/in-page.ts
@@ -259,63 +259,107 @@ export function annotateInPage(doc: Document): AnnotateInPage {
* whatever the page put there: a filled password box, a token in a hidden
* input, an api-key data attribute. Redaction happens on a clone here, in
* the guest, so the secret never reaches the host, the composer, or the
- * model — the same reason `browser_type` masks what it types.
+ * model. Same reason `browser_type` masks what it types.
+ *
+ * Walk every descendant, not just form controls. A comment on a parent of a
+ * `data-api-key` node still serializes that child. Also clear the live
+ * `.value` of secret-shaped fields: typed passwords and secret textareas do
+ * not always show up as attributes. Target text is taken from this same
+ * clone so a textarea body cannot leak after the HTML is clean.
*/
- const markupOf = (el: Element): string => {
+ const secretName = /key|token|secret|password|auth|session|credential/
+
+ const looksSecret = (value: string): boolean => secretName.test(value.toLowerCase())
+
+ const isSecretControl = (node: Element): boolean => {
+ const tag = node.tagName.toLowerCase()
+ const type = (node.getAttribute('type') || '').toLowerCase()
+
+ if (tag === 'input' && (type === 'password' || type === 'hidden')) {
+ return true
+ }
+
+ if (tag === 'input' || tag === 'textarea' || tag === 'select') {
+ return (
+ looksSecret(node.getAttribute('name') || '') ||
+ looksSecret(node.id || '') ||
+ looksSecret(node.getAttribute('autocomplete') || '')
+ )
+ }
+
+ return node.hasAttribute('data-secret')
+ }
+
+ const clearControlValue = (node: Element): void => {
+ const tag = node.tagName.toLowerCase()
+
+ if (tag === 'input' || tag === 'select') {
+ const field = node as HTMLInputElement
+ field.value = '[redacted]'
+ node.setAttribute('value', '[redacted]')
+ }
+
+ if (tag === 'textarea') {
+ const field = node as HTMLTextAreaElement
+ field.value = '[redacted]'
+ node.textContent = '[redacted]'
+ }
+
+ if (node.hasAttribute('data-secret') && tag !== 'input' && tag !== 'textarea' && tag !== 'select') {
+ node.textContent = '[redacted]'
+ }
+ }
+
+ const redactClone = (el: Element): Element | null => {
let clone: Element
try {
clone = el.cloneNode(true) as Element
} catch {
- return ''
+ return null
}
const nodes: Element[] = [clone]
- const nested = clone.querySelectorAll('input, textarea, select, [data-secret]')
+ const nested = clone.querySelectorAll('*')
for (let i = 0; i < nested.length; i++) {
nodes.push(nested[i])
}
for (const node of nodes) {
- const tag = node.tagName.toLowerCase()
- const type = (node.getAttribute('type') || '').toLowerCase()
- const secretField = tag === 'input' && (type === 'password' || type === 'hidden')
const names = node.getAttributeNames()
for (const name of names) {
- const lower = name.toLowerCase()
-
- if (lower === 'value' && (secretField || node.getAttribute('value'))) {
- node.setAttribute(name, secretField ? '[redacted]' : node.getAttribute(name) || '')
- }
-
- if (/key|token|secret|password|auth|session|credential/.test(lower)) {
+ if (looksSecret(name)) {
node.setAttribute(name, '[redacted]')
}
}
- if (secretField) {
- node.setAttribute('value', '[redacted]')
+ if (isSecretControl(node)) {
+ clearControlValue(node)
}
}
- const html = clone.outerHTML || ''
+ return clone
+ }
+ const budgetHtml = (html: string): string => {
if (html.length <= htmlBudget) {
return html
}
- // Keep the opening tag — where the classes and props live — over the tail.
+ // Keep the opening tag, where the classes and props live, over the tail.
return `${html.slice(0, htmlBudget - 1)}…`
}
const identityOf = (el: Element): AnnotatePageIdentity => {
- const text = (el.textContent || '').replace(/\s+/g, ' ').trim()
+ const clone = redactClone(el)
+ const html = clone ? budgetHtml(clone.outerHTML || '') : ''
+ const text = ((clone ?? el).textContent || '').replace(/\s+/g, ' ').trim()
return {
css: readCss(el),
- html: markupOf(el),
+ html,
selector: cssPath(el),
tag: el.tagName.toLowerCase(),
text: text.length > 80 ? `${text.slice(0, 79)}…` : text
diff --git a/apps/desktop/src/lib/preview-annotate/pack.test.ts b/apps/desktop/src/lib/preview-annotate/pack.test.ts
index c747bec6fc9..741cd0d821c 100644
--- a/apps/desktop/src/lib/preview-annotate/pack.test.ts
+++ b/apps/desktop/src/lib/preview-annotate/pack.test.ts
@@ -258,4 +258,36 @@ describe('annotateFlushPrompt batching', () => {
expect(prompt).toContain('Unanchored (dragged areas) (1 comment)')
})
+
+ it('stays flat when a container comment owns the comments nested inside it', () => {
+ const prompt = annotateFlushPrompt(
+ packageAnnotateStack([
+ at(1, 'body>main'),
+ at(2, 'body>main>section.hero>h1'),
+ at(3, 'body>main>section.pricing>button'),
+ at(4, 'body>main>section.faq>li')
+ ])
+ )
+
+ expect(prompt).not.toContain('Group 1')
+ expect(prompt).not.toContain('separate files')
+ expect(prompt).not.toContain('delegate whole groups')
+ })
+
+ it('does not claim nested regions are separate files', () => {
+ const prompt = annotateFlushPrompt(
+ packageAnnotateStack([
+ at(1, 'body>header.nav>a.logo'),
+ at(2, 'body>header.nav>ul.links'),
+ at(3, 'body>main'),
+ at(4, 'body>main>section.hero>h1'),
+ at(5, 'body>main>section.pricing>button')
+ ])
+ )
+
+ expect(prompt).toContain('Group 1 — `header.nav` (2 comments)')
+ expect(prompt).toContain('Group 2 — `main` (3 comments)')
+ expect(prompt).toContain('Work them as 2 pieces of work, not 5.')
+ expect(prompt).not.toContain('Group 3')
+ })
})