Skip to content

Your team of AI agents, on your Mac, Windows or Linux. Agents that talk in channels, write code, review each other and use your tools, on the Claude Code, Codex, OpenCode or Pi you already have. Anything that touches the real world waits for your yes.

Merge commit from fork

Eduardo Machado329d7746930a
diff --git a/src/core/browser.ts b/src/core/browser.ts
index f7d5595..999d32c 100644
--- a/src/core/browser.ts
+++ b/src/core/browser.ts
@@ -53,14 +53,17 @@ export const browserTools = (): ToolDef[] => {
{
name: 'navegador_digitar',
description: L(
- 'Escreve num campo (troca o que já tem nele) ou escolhe uma opção numa lista. Com enter: true, aperta Enter depois (ex.: pra buscar).',
- 'Types in a field (replacing what is in it) or picks an option in a list. With enter: true, presses Enter afterwards (e.g. to search).'
+ 'Escreve num campo (troca o que já tem nele) ou escolhe uma opção numa lista. Com enter: true, aperta Enter depois (ex.: pra buscar). Onde Enter envia (um comentário, uma mensagem, um formulário que publica), o texto entra e o Enter vira pedido de aprovação.',
+ 'Types in a field (replacing what is in it) or picks an option in a list. With enter: true, presses Enter afterwards (e.g. to search). Where Enter sends (a comment, a message, a form that publishes), the text goes in and the Enter becomes an approval request.'
),
inputSchema: { type: 'object', properties: { alvo, texto: { type: 'string' }, enter: { type: 'boolean' } }, required: ['alvo', 'texto'] }
},
{
name: 'navegador_tecla',
- description: L(`Aperta uma tecla: ${KEYS.join(', ')}.`, `Presses a key: ${KEYS.join(', ')}.`),
+ description: L(
+ `Aperta uma tecla: ${KEYS.join(', ')}. Enter ou espaço num botão que publica, envia ou apaga (ou sem nome), ou Enter num campo que envia, vira pedido de aprovação, como o clique.`,
+ `Presses a key: ${KEYS.join(', ')}. Enter or space on a button that publishes, sends or deletes (or has no name), or Enter in a field that sends, becomes an approval request, like the click.`
+ ),
inputSchema: { type: 'object', properties: { tecla: { type: 'string' } }, required: ['tecla'] }
},
{
@@ -118,10 +121,30 @@ export function bareTarget(target: string): string {
// What buys, pays, publishes, sends, schedules, saves or deletes, by the words on it.
const RISKY =
- /\b(compr(ar|e|a)|finalizar (compra|pedido)|checkout|buy|purchase|pag(ar|ue)|pay|publi(car|que|sh)|postar|poste|post|enviar|envie|send|submit|confirm(ar|e)?|agend(ar|e)|schedule|salvar|save|coment(ar|e)|comment|responder|reply|exclu(ir|a)|apag(ar|ue)|delet(ar|e)|remov(er|a|e)|reserv(ar|e)|book|transferir|transfer|doar|donate|inscrever|subscribe|seguir|follow)\b/
+ /\b(compr(ar|e|a)|finalizar (compra|pedido)|checkout|buy|purchase|pag(ar|ue)|pay|publi(car|que|sh)|postar|poste|post|enviar|envie|send|submit|confirm(ar|e)?|agend(ar|e)|schedule|salvar|save|coment(ar|e)|comment|responder|reply|exclu(ir|a)|apag(ar|ue)|delet(ar|e)|remov(er|a|e)|reserv(ar|e)|book|transferir|transfer|doar|donate|inscrever|subscribe|seguir|follow|repost(ar|e)?|retweet(ar)?|tweet(ar)?|curt(ir|a)|like|compartilh(ar|e)|share)\b/
export const risky = (...texts: string[]): boolean => texts.some((t) => RISKY.test(norm(t)))
+const SEARCH = /\b(busc|pesquis|procur|search|find|filtr|go\b|ir\b)/
+// What Enter in a field would do, when that could publish, send or delete: in a text area or an
+// editable block (a comment, a message, where Enter often sends), or in a form that sends with a
+// risky button, or with a nameless one unless the field is a search. A search box goes on.
+export function enterSends(f: Pick<BrowserElement, 'label' | 'multiline' | 'submits'>): boolean {
+ if (f.multiline) return true
+ if (f.submits === undefined) return false
+ return f.submits ? risky(f.submits) : !SEARCH.test(norm(f.label))
+}
+
+// Enter or Space on the focused element, when it could publish, send or delete: a field where Enter
+// sends (enterSends), or a button or link with a risky name or none at all. Toggles, tabs and
+// options only change what's on the page.
+export function keyActs(key: string, el: BrowserElement | undefined): boolean {
+ if (!el || (key !== 'enter' && key !== 'space')) return false
+ if (el.role === 'campo') return key === 'enter' && enterSends(el)
+ if (['checkbox', 'radio', 'chave', 'opção', 'aba', 'lista', 'controle'].includes(el.role)) return false
+ return !el.label || risky(el.label)
+}
+
// The element named by number, by its exact text, or by the only text that contains it.
export function findByText(target: string, elements: BrowserElement[]): BrowserElement | undefined {
const num = /^#?\s*(\d+)$/.exec(target.trim()) ?? /^#\s*(\d+)\b/.exec(target.trim()) // "#9" or "#9 botão Buscar"
@@ -382,18 +405,14 @@ export class Browser {
const page = await this.page(id, !!this.deps.jev?.on())
const spot = await this.locate(target, page)
if ('error' in spot) return { result: textResult(spot.error, true) }
- const label = 'el' in spot ? spot.el.label : target
- this.update(id, { doing: { label: L('Clicando em', 'Clicking'), detail: label || target } })
- if (risky(label || target)) {
- const shot = page.frame ? { frame: page.frame } : await this.deps.host(id, 'frame')
- const artifact = shot.frame ? this.keep(id, ctx, Buffer.from(shot.frame, 'base64'), L(`Antes de clicar em "${label}"`, `Before clicking "${label}"`), page.url) : undefined
- const why = typeof args['motivo'] === 'string' ? args['motivo'].trim() : ''
- const callArgs: Record<string, unknown> = { url: page.url, alvo: label, ...('x' in spot && page.w && page.h ? { x: spot.x / page.w, y: spot.y / page.h } : {}) }
- return {
- result: textResult(L(`Esse clique ("${label}") precisa de aprovação.`, `This click ("${label}") needs approval.`)),
- artifact,
- approval: { args: callArgs, why: why || L(`Clicar em "${label}" em ${page.title || page.url}`, `Click "${label}" on ${page.title || page.url}`), detail: L(`Clicar em "${label}"`, `Click "${label}"`) }
- }
+ // Judged by the page's own words only, never by how the agent named it: an element with
+ // no name, or a spot found only on the screen, can't be told safe, so it asks.
+ const label = 'el' in spot ? spot.el.label : ''
+ const named = label || L(`${target} (sem nome na página)`, `${target} (no name on the page)`)
+ this.update(id, { doing: { label: L('Clicando em', 'Clicking'), detail: named } })
+ if (!label || risky(label)) {
+ const callArgs: Record<string, unknown> = { url: page.url, alvo: label, ...('x' in spot && page.w && page.h ? { x: spot.x / page.w, y: spot.y / page.h } : {}), ...('el' in spot && !label ? { ref: spot.ref } : {}) }
+ return this.ask(id, ctx, page, args, callArgs, L(`Clicar em "${named}"`, `Click "${named}"`), L(`Esse clique ("${named}") precisa de aprovação.`, `This click ("${named}") needs approval.`))
}
const r = await this.deps.host(id, 'click', 'el' in spot ? { ref: spot.ref } : { x: spot.x, y: spot.y })
return { result: await this.after(id, r, { ...step, detail: label || target }), detail: label || target }
@@ -407,12 +426,28 @@ export class Browser {
if ('error' in spot) return { result: textResult(spot.error, true) }
if (!('el' in spot)) return { result: textResult(L('Achei o lugar só pela imagem; clique nele com navegador_clicar e use o número do campo.', 'I found the spot only in the image; click it with navegador_clicar and use the field number.'), true) }
this.update(id, { doing: { label: L('Escrevendo em', 'Typing in'), detail: spot.el.label || target } })
- const r = await this.deps.host(id, 'type', { ref: spot.ref, text: String(args['texto'] ?? ''), enter: args['enter'] === true })
+ // Enter where it sends: the text goes in now, and the Enter waits for an approval.
+ const sends = args['enter'] === true && enterSends(spot.el)
+ const r = await this.deps.host(id, 'type', { ref: spot.ref, text: String(args['texto'] ?? ''), enter: args['enter'] === true && !sends })
+ if (sends) {
+ this.seen(id, r, { ...step, detail: spot.el.label || target })
+ const field = spot.el.label || L('o campo', 'the field')
+ return this.ask(id, ctx, { ...page, frame: undefined }, args, { url: page.url, tecla: 'enter', alvo: spot.el.label, ref: spot.ref }, L(`Apertar Enter em "${field}"`, `Press Enter in "${field}"`), L(`Escrevi em "${field}". Apertar Enter aí envia, então precisa de aprovação.`, `I typed in "${field}". Pressing Enter there sends it, so it needs approval.`))
+ }
return { result: await this.after(id, r, { ...step, detail: spot.el.label || target }), detail: spot.el.label || target }
}
case 'navegador_tecla': {
const key = String(args['tecla'] ?? '').toLowerCase().replace(/[^a-z]/g, '')
if (!KEYS.includes(key)) return { result: textResult(L(`Tecla desconhecida. Use uma destas: ${KEYS.join(', ')}.`, `Unknown key. Use one of these: ${KEYS.join(', ')}.`), true) }
+ if (key === 'enter' || key === 'space') {
+ const page = await this.page(id, false)
+ const focused = (page.elements ?? []).find((e) => e.focused)
+ if (keyActs(key, focused)) {
+ const what = focused!.label || L('um elemento sem nome', 'an element with no name')
+ const k = key === 'enter' ? 'Enter' : L('Espaço', 'Space')
+ return this.ask(id, ctx, page, args, { url: page.url, tecla: key, alvo: focused!.label, ref: focused!.ref }, L(`Apertar ${k} em "${what}"`, `Press ${k} on "${what}"`), L(`Apertar ${k} em "${what}" precisa de aprovação.`, `Pressing ${k} on "${what}" needs approval.`))
+ }
+ }
return { result: await this.after(id, await this.deps.host(id, 'key', { key }), step) }
}
case 'navegador_rolar': {
@@ -461,7 +496,15 @@ export class Browser {
}
}
- // An approved click: only on the same page, on the element with that text (or the same spot).
+ // An action that waits for me: the screen as it is now, kept with the request.
+ private async ask(id: string, ctx: Ctx, page: BrowserReply, args: Record<string, unknown>, callArgs: Record<string, unknown>, detail: string, said: string): Promise<BrowserOutcome> {
+ const shot = page.frame ? { frame: page.frame } : await this.deps.host(id, 'frame')
+ const artifact = shot.frame ? this.keep(id, ctx, Buffer.from(shot.frame, 'base64'), L(`Antes de: ${detail}`, `Before: ${detail}`), page.url) : undefined
+ const why = typeof args['motivo'] === 'string' ? args['motivo'].trim() : ''
+ return { result: textResult(said), artifact, approval: { args: callArgs, why: why || `${detail} ${L('em', 'on')} ${page.title || page.url}`, detail } }
+ }
+
+ // An approved click or key: only on the same page, on the element with that text (or the same spot).
async approved(agent: Agent, args: Record<string, unknown>): Promise<{ ok: boolean; text: string }> {
const url = String(args['url'] ?? '')
const target = String(args['alvo'] ?? '')
@@ -470,12 +513,16 @@ export class Browser {
const snap = await this.deps.host(agent.id, 'snapshot')
if (!sameUrl(snap.url, url)) return { ok: false, text: L(`A página mudou desde o pedido (agora está em ${snap.url}). Nada foi clicado.`, `The page changed since the request (it's now at ${snap.url}). Nothing was clicked.`) }
let r: BrowserReply
+ const key = typeof args['tecla'] === 'string' ? args['tecla'] : undefined
if (typeof args['x'] === 'number' && typeof args['y'] === 'number' && snap.w && snap.h) r = await this.deps.host(agent.id, 'click', { x: args['x'] * snap.w, y: args['y'] * snap.h })
else {
- const same = (snap.elements ?? []).filter((e) => norm(e.label) === norm(target))
- const el = same.find((e) => e.inView) ?? same[0]
- if (!el) return { ok: false, text: L(`"${target}" não está mais na página. Nada foi clicado.`, `"${target}" is no longer on the page. Nothing was clicked.`) }
+ // An element with no name is the same one only at the same number, still with no name.
+ const same = target ? (snap.elements ?? []).filter((e) => norm(e.label) === norm(target)) : (snap.elements ?? []).filter((e) => e.ref === args['ref'] && !e.label)
+ const el = same.find((e) => e.ref === args['ref']) ?? same.find((e) => e.inView) ?? same[0]
+ if (!el) return { ok: false, text: L(`"${target || '#' + String(args['ref'])}" não está mais na página. Nada foi feito.`, `"${target || '#' + String(args['ref'])}" is no longer on the page. Nothing was done.`) }
+ // A key on a field: back in the field, then the key. On a button, Enter or Space is its click.
r = await this.deps.host(agent.id, 'click', { ref: el.ref })
+ if (key && el.role === 'campo') r = await this.deps.host(agent.id, 'key', { key })
}
return { ok: true, text: await this.after(agent.id, r, { label: L('Clicou (aprovado)', 'Clicked (approved)'), detail: target }).then((x) => (x.content[0] as { text: string }).text) }
} catch (e) {
diff --git a/src/core/runs.ts b/src/core/runs.ts
index 5256357..dd8158a 100644
--- a/src/core/runs.ts
+++ b/src/core/runs.ts
@@ -1763,7 +1763,9 @@ export class Runner {
}
} else if (ap.connectorId === NAVEGADOR) {
// A click in the agent's browser: made only on the same page, on the same button.
- const what = L(`clicar em "${String(ap.args['alvo'] ?? '')}"`, `clicking "${String(ap.args['alvo'] ?? '')}"`)
+ const alvo = String(ap.args['alvo'] ?? '') || L('um elemento sem nome', 'an element with no name')
+ const key = typeof ap.args['tecla'] === 'string' ? (ap.args['tecla'] === 'enter' ? 'Enter' : L('Espaço', 'Space')) : undefined
+ const what = key ? L(`apertar ${key} em "${alvo}"`, `pressing ${key} on "${alvo}"`) : L(`clicar em "${alvo}"`, `clicking "${alvo}"`)
if (decision === 'approved' && agent?.browser && this.deps.browser) {
const r = await this.deps.browser.approved(agent, ap.args)
ok = r.ok
diff --git a/src/shared/page.ts b/src/shared/page.ts
index a52b854..ca55ac2 100644
--- a/src/shared/page.ts
+++ b/src/shared/page.ts
@@ -12,6 +12,17 @@ export const SNAPSHOT = `(() => {
// "Tudo Tudo": a visible label and a hidden copy for screen readers.
const once = (s) => { const w = s.split(' '); const h = w.length / 2; return w.length % 2 === 0 && w.slice(0, h).join(' ') === w.slice(h).join(' ') ? w.slice(0, h).join(' ') : s }
const ROLES = { button: 'botão', tab: 'aba', menuitem: 'item de menu', menuitemcheckbox: 'item de menu', option: 'opção', combobox: 'campo', textbox: 'campo', searchbox: 'campo', switch: 'chave', slider: 'controle' }
+ // The element that has the focus, inside shadow roots too.
+ let active = document.activeElement
+ while (active && active.shadowRoot && active.shadowRoot.activeElement) active = active.shadowRoot.activeElement
+ // What a field's form sends with: its submit button's label (Enter in the field presses it).
+ const sender = (f) => {
+ const form = f.form || (f.closest && f.closest('form'))
+ if (!form) return undefined
+ const b = form.querySelector('button:not([type]),button[type=submit],input[type=submit],input[type=image]')
+ if (!b) return ''
+ return clean(b.getAttribute('aria-label')) || clean(b.innerText) || clean(b.value) || clean(b.getAttribute('title')) || clean(b.getAttribute('alt'))
+ }
const byIds = (ids) => clean((ids || '').split(/\\s+/).map((id) => { const n = id && (el.getRootNode().getElementById ? el.getRootNode() : document).getElementById(id); return n ? n.innerText || n.textContent : '' }).join(' '))
let el
for (el of found) {
@@ -31,7 +42,8 @@ export const SNAPSHOT = `(() => {
else if (el.isContentEditable) value = clean(el.innerText).slice(0, 80)
const c = el.checked !== undefined && (type === 'checkbox' || type === 'radio') ? el.checked : el.getAttribute('aria-checked') === 'true' || el.getAttribute('aria-selected') === 'true' ? true : undefined
refs.push(new WeakRef(el))
- out.push({ ref: refs.length, role, label: once(label).slice(0, 100), value: value || undefined, checked: c, disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true' || undefined, inView: r.bottom > 0 && r.right > 0 && r.top < H && r.left < W })
+ const submits = field && tag === 'input' ? sender(el) : undefined
+ out.push({ ref: refs.length, role, label: once(label).slice(0, 100), value: value || undefined, checked: c, disabled: el.disabled === true || el.getAttribute('aria-disabled') === 'true' || undefined, inView: r.bottom > 0 && r.right > 0 && r.top < H && r.left < W, focused: el === active || undefined, multiline: (field && (tag === 'textarea' || el.isContentEditable)) || undefined, submits: submits === undefined ? undefined : submits.slice(0, 100) })
}
window.__adRefs = refs
return { url: location.href, title: document.title, w: W, h: H, scrollY: Math.round(scrollY), scrollH: document.documentElement.scrollHeight, elements: out }
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 6db099c..45e04ad 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -328,6 +328,9 @@ export interface BrowserElement {
checked?: boolean
disabled?: boolean
inView: boolean
+ focused?: boolean // where a key goes now
+ multiline?: boolean // a text area or an editable block: Enter there often sends (a comment, a message)
+ submits?: string // a field in a form: the label of the button that sends it (what Enter does)
}
export interface BrowserReply {
diff --git a/test/browser.test.ts b/test/browser.test.ts
index 258e909..53076a8 100644
--- a/test/browser.test.ts
+++ b/test/browser.test.ts
@@ -4,7 +4,7 @@ import { join } from 'node:path'
import { beforeEach, describe, expect, it } from 'vitest'
import type { CoreEvent } from '../src/shared/rpc'
import type { Agent, BrowserElement, BrowserReply, Settings } from '../src/shared/types'
-import { bareTarget, Browser, browserStep, describePage, findByText, risky, type BrowserHost } from '../src/core/browser'
+import { bareTarget, enterSends, keyActs, Browser, browserStep, describePage, findByText, risky, type BrowserHost } from '../src/core/browser'
import { systemPrompt } from '../src/core/context'
import { Db } from '../src/core/db'
import { callTool, fakeEngine } from '../src/core/engines/fake'
@@ -35,14 +35,14 @@ const el = (ref: number, role: string, label: string, extra: Partial<BrowserElem
const ELEMENTS = [el(1, 'campo', 'Destino', { value: '' }), el(2, 'botão', 'Buscar'), el(3, 'botão', 'Publicar'), el(4, 'link', 'Ajuda', { inView: false }), el(5, 'botão', ''), el(6, 'link', 'Buscar ajuda', { inView: false })]
// A page in memory: what the main process would do in Chromium, recorded.
-function fakeHost(): { host: BrowserHost; calls: { op: string; args?: Record<string, unknown> }[]; page: { url: string; title: string; shown: boolean } } {
- const page = { url: '', title: '', shown: false }
+function fakeHost(): { host: BrowserHost; calls: { op: string; args?: Record<string, unknown> }[]; page: { url: string; title: string; shown: boolean; elements: BrowserElement[] } } {
+ const page = { url: '', title: '', shown: false, elements: ELEMENTS }
const calls: { op: string; args?: Record<string, unknown> }[] = []
const host: BrowserHost = async (_agentId, op, args) => {
calls.push({ op, args })
const here: BrowserReply = { url: page.url, title: page.title, frame: Buffer.from('jpeg').toString('base64'), w: 1280, h: 800, shown: page.shown }
if (op === 'open') Object.assign(page, { url: String(args?.['url']), title: 'Studio' })
- if (op === 'snapshot') return { ...here, frame: undefined, elements: ELEMENTS }
+ if (op === 'snapshot') return { ...here, frame: undefined, elements: page.elements }
if (op === 'text') return { ...here, text: 'Retenção média 42%' }
return { ...here, url: page.url, title: page.title }
}
@@ -67,6 +67,24 @@ describe('finding what the agent names', () => {
it('knows what buys, publishes, sends or deletes, by the words on it', () => {
for (const w of ['Publicar', 'Comprar agora', 'Finalizar compra', 'Enviar', 'Agendar', 'Salvar', 'Excluir vídeo', 'Post', 'Submit', 'Reservar']) expect(risky(w), w).toBe(true)
for (const w of ['Buscar', 'Análises', 'Próximo', 'Posts', 'Facebook', 'Cancelar', 'Fechar']) expect(risky(w), w).toBe(false)
+ // Public actions on the person's account too (GHSA-4q39)
+ for (const w of ['Repost', 'Repostar', 'Curtir', 'Like', 'Retweet', 'Tweet', 'Compartilhar', 'Share']) expect(risky(w), w).toBe(true)
+ })
+
+ it('knows when Enter or Space would send something (GHSA-4q39)', () => {
+ expect(enterSends({ label: 'Destino' })).toBe(false) // no form: a search or a filter
+ expect(enterSends({ label: 'Comentar', multiline: true })).toBe(true) // a comment box: Enter sends
+ expect(enterSends({ label: 'Mensagem', submits: 'Enviar' })).toBe(true)
+ expect(enterSends({ label: 'Pesquisar', submits: 'Buscar' })).toBe(false)
+ expect(enterSends({ label: 'Pesquisar', submits: '' })).toBe(false) // a search with a magnifier button
+ expect(enterSends({ label: 'Nome', submits: '' })).toBe(true) // a nameless button that isn't a search
+ expect(keyActs('enter', el(3, 'botão', 'Publicar'))).toBe(true)
+ expect(keyActs('space', el(5, 'botão', ''))).toBe(true) // no name: can't be told safe
+ expect(keyActs('enter', el(2, 'botão', 'Buscar'))).toBe(false)
+ expect(keyActs('space', el(7, 'checkbox', 'Lembrar'))).toBe(false)
+ expect(keyActs('space', el(8, 'campo', 'Comentar', { multiline: true }))).toBe(false) // a space in the text
+ expect(keyActs('tab', el(3, 'botão', 'Publicar'))).toBe(false)
+ expect(keyActs('enter', undefined)).toBe(false)
})
it('describes the page with what is on screen, numbered', () => {
@@ -169,6 +187,45 @@ describe("an agent's browser", () => {
expect(fake.calls.filter((c) => c.op === 'click')).toHaveLength(1)
})
+ it('Enter where it sends waits for me, after the text goes in; approved, it presses it in that field (GHSA-4q39)', async () => {
+ fake.page.elements = [el(1, 'campo', 'Adicione um comentário', { multiline: true, value: '' }), el(2, 'botão', 'Responder')]
+ await browser.call(lia(), 'navegador_abrir', { url: 'https://x.com/post/1' }, ctx)
+ const r = await browser.call(lia(), 'navegador_digitar', { alvo: '#1', texto: 'Ótimo post!', enter: true }, ctx)
+ expect(r.approval).toMatchObject({ args: { url: 'https://x.com/post/1', tecla: 'enter', alvo: 'Adicione um comentário', ref: 1 }, detail: 'Apertar Enter em "Adicione um comentário"' })
+ expect(r.artifact?.kind).toBe('image')
+ expect(fake.calls.filter((c) => c.op === 'type').map((c) => c.args)).toEqual([{ ref: 1, text: 'Ótimo post!', enter: false }])
+ expect(fake.calls.some((c) => c.op === 'key')).toBe(false)
+ expect(await browser.approved(lia(), r.approval!.args)).toMatchObject({ ok: true })
+ expect(fake.calls.filter((c) => c.op === 'click' || c.op === 'key').map((c) => [c.op, c.args])).toEqual([['click', { ref: 1 }], ['key', { key: 'enter' }]])
+ })
+
+ it('Enter or Space on a focused button that publishes, or has no name, waits for me (GHSA-4q39)', async () => {
+ await browser.call(lia(), 'navegador_abrir', { url: 'https://x.com/compose' }, ctx)
+ fake.page.elements = [el(1, 'campo', 'Texto'), el(2, 'botão', 'Postar', { focused: true })]
+ const r = await browser.call(lia(), 'navegador_tecla', { tecla: 'enter' }, ctx)
+ expect(r.approval).toMatchObject({ args: { tecla: 'enter', alvo: 'Postar', ref: 2 }, detail: 'Apertar Enter em "Postar"' })
+ fake.page.elements = [el(1, 'botão', '', { focused: true })]
+ expect((await browser.call(lia(), 'navegador_tecla', { tecla: 'space' }, ctx)).approval?.detail).toBe('Apertar Espaço em "um elemento sem nome"')
+ expect(fake.calls.some((c) => c.op === 'key')).toBe(false)
+ // Approved: the same button, clicked (Enter on a button is its click).
+ fake.page.elements = [el(1, 'campo', 'Texto'), el(2, 'botão', 'Postar', { focused: true })]
+ expect(await browser.approved(lia(), r.approval!.args)).toMatchObject({ ok: true })
+ expect(fake.calls.filter((c) => c.op === 'click').map((c) => c.args)).toEqual([{ ref: 2 }])
+ // Tab and a focus on something harmless go on as before.
+ fake.page.elements = [el(1, 'botão', 'Buscar', { focused: true })]
+ expect((await browser.call(lia(), 'navegador_tecla', { tecla: 'enter' }, ctx)).approval).toBeUndefined()
+ expect((await browser.call(lia(), 'navegador_tecla', { tecla: 'tab' }, ctx)).approval).toBeUndefined()
+ })
+
+ it('a click on something with no name on the page waits for me, whatever the agent calls it (GHSA-4q39)', async () => {
+ await browser.call(lia(), 'navegador_abrir', { url: 'https://x.com/compose' }, ctx)
+ const r = await browser.call(lia(), 'navegador_clicar', { alvo: '#5' }, ctx)
+ expect(r.approval).toMatchObject({ args: { url: 'https://x.com/compose', alvo: '', ref: 5 } })
+ expect(fake.calls.some((c) => c.op === 'click')).toBe(false)
+ expect(await browser.approved(lia(), r.approval!.args)).toMatchObject({ ok: true })
+ expect(fake.calls.filter((c) => c.op === 'click').map((c) => c.args)).toEqual([{ ref: 5 }])
+ })
+
it('reads the whole page as information, not instructions', async () => {
await browser.call(lia(), 'navegador_abrir', { url: 'https://studio.youtube.com' }, ctx)
const r = await browser.call(lia(), 'navegador_ler', {}, ctx)
@@ -194,7 +251,7 @@ describe("an agent's browser", () => {
expect(browser.view('lia-0001')?.log.at(-1)?.label).toBe('Edu devolveu')
})
- it('with Jev on, what the text does not find goes to Jev: first the elements, then the screen', async () => {
+ it('with Jev on, what the text does not find goes to Jev: first the elements, then the screen; with no name to judge by, it waits for me', async () => {
const asked: Record<string, unknown>[] = []
let answer: unknown = { answers: { alvo: { choice: 'e5', probabilities: { e5: 0.9 } } } }
const f = (async (_url: string, init?: RequestInit) => {
@@ -204,9 +261,13 @@ describe("an agent's browser", () => {
const withJev = new Browser({ host: fake.host, db, dataDir, emit: () => {}, me: () => 'Edu', jev: { key: async () => 'ts-key', on: () => true, fetch: f } })
await withJev.call(lia(), 'navegador_abrir', { url: 'https://airbnb.com' }, ctx)
- await withJev.call(lia(), 'navegador_clicar', { alvo: 'o ícone de menu no canto' }, ctx)
+ const menu = await withJev.call(lia(), 'navegador_clicar', { alvo: 'o ícone de menu no canto' }, ctx)
expect(asked[0]).toMatchObject({ model: 'jev-latest', state: { pedido: 'o ícone de menu no canto' }, questions: { alvo: { type: 'choice' } } })
expect((asked[0]!['questions'] as { alvo: { criteria: Record<string, string> } }).alvo.criteria).toMatchObject({ e2: 'botão "Buscar"', e5: 'botão sem nome', e4: 'link "Ajuda" (fora da tela)' })
+ // The element Jev found has no name on the page: what the agent called it doesn't make it safe.
+ expect(menu.approval).toMatchObject({ args: { alvo: '', ref: 5 } })
+ expect(fake.calls.some((c) => c.op === 'click')).toBe(false)
+ expect(await withJev.approved(lia(), menu.approval!.args)).toMatchObject({ ok: true })
expect(fake.calls.filter((c) => c.op === 'click').at(-1)?.args).toEqual({ ref: 5 })
// Not among the elements: the box on the screenshot, clicked at its center.
@@ -218,8 +279,13 @@ describe("an agent's browser", () => {
return Response.json(n++ === 0 ? { answers: { alvo: { choice: '__nenhum' } } } : { answers: { alvo: { box: { left: 0.5, right: 0.6, top: 0.1, bottom: 0.2 }, confidence: 0.8 } } })
}) as unknown as typeof fetch
const onScreen = new Browser({ host: fake.host, db, dataDir, emit: () => {}, me: () => 'Edu', jev: { key: async () => 'ts-key', on: () => true, fetch: f2 } })
- await onScreen.call(lia(), 'navegador_clicar', { alvo: 'o pin do mapa perto do lago' }, ctx)
+ const pin = await onScreen.call(lia(), 'navegador_clicar', { alvo: 'o pin do mapa perto do lago' }, ctx)
expect(asked.at(-1)).toMatchObject({ model: 'jev-preview', questions: { alvo: { type: 'box' } } })
+ // A spot found only on the screen waits for me too; approved, it's clicked there.
+ expect(pin.approval?.args).toMatchObject({ alvo: '' })
+ expect(pin.approval!.args['x'] as number).toBeCloseTo(0.55)
+ expect(pin.approval!.args['y'] as number).toBeCloseTo(0.15)
+ expect(await onScreen.approved(lia(), pin.approval!.args)).toMatchObject({ ok: true })
const click = fake.calls.filter((c) => c.op === 'click').at(-1)!.args as { x: number; y: number }
expect(click.x).toBeCloseTo(0.55 * 1280)
expect(click.y).toBeCloseTo(0.15 * 800)