Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠
JavaScript ai-agentai-agentsai-toolsbrowser-aibrowser-automationbrowser-extensionchrome-aichrome-devtoolschrome-extensionchrome-extensionsfirefox-addonfirefox-addonsfirefox-extensionfirefox-extensionsgemmagemma4minimaxoffline-aioffline-llmqwen
Side panel: closing quotes end a link; quieter link style
Emre Sokullua862d647de5d
diff --git a/src/chrome/src/ui/markdown-link.js b/src/chrome/src/ui/markdown-link.jsindex b8481f26c..e7e2e5dc9 100644--- a/src/chrome/src/ui/markdown-link.js+++ b/src/chrome/src/ui/markdown-link.js@@ -29,6 +29,12 @@ const SAFE_SCHEMES = new Set(['http', 'https', 'mailto']);const MD_LINK_RE = /\[([^\]]+)\]\(((?:[^()]|\([^()]*\))*)\)/g;+// A bare URL ends at whitespace, markup, an escaped quote, or punctuation that+// only closes prose. Curly quotes, guillemets and CJK punctuation appear+// percent-encoded in real URLs; inside a host they would be IDN-encoded, so+// “https://example.com” must not link to example.xn--com-….+const PLAIN_URL_RE = /\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`“”‘’„‚«»‹›「」『』【】〔〕〈〉《》()[]{}、。,;:!?])+/gi;+/*** Sanitize a single markdown link. Returns either a safe <a> string or* the bare label text when the URL is unsafe / unrecognized.@@ -121,7 +127,7 @@ export function linkifyPlainUrls(html, precedingText = '') {return token;}if (protectedDepth) return token;- return token.replace(/\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`])+/gi, (candidate, offset, source) => {+ return token.replace(PLAIN_URL_RE, (candidate, offset, source) => {const absoluteOffset = precedingText.length + tokenOffset + offset;if (imageRanges.some(([start, end]) => absoluteOffset >= start && absoluteOffset < end)) return candidate;// Do not turn a URL embedded in another scheme or word into a new link.@@ -143,7 +149,7 @@ export function linkifyPlainUrls(html, precedingText = '') {continue;}if (last === ';' && /&(?:amp|#\d+|#x[\da-f]+);$/i.test(candidate.slice(0, end))) break;- if (/[.,!?;:]/.test(last)) { end--; continue; }+ if (/[.,!?;:…]/.test(last)) { end--; continue; }const opening = pairs[last];if (opening && balance[opening] < 0) { balance[opening]++; end--; continue; }break;diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.jsindex f70f7726f..ea69d4146 100644--- a/src/chrome/src/ui/sidepanel.js+++ b/src/chrome/src/ui/sidepanel.js@@ -4405,7 +4405,7 @@ function trimScheduleUrlProse(raw) {for (;;) {const last = url.slice(-1);const opener = last === ')' ? '(' : last === ']' ? '[' : '';- if (/[.,;:!?]/.test(last) || (opener && url.split(last).length > url.split(opener).length)) {+ if (/[.,;:!?…]/.test(last) || (opener && url.split(last).length > url.split(opener).length)) {url = url.slice(0, -1);} else {return url;@@ -4414,10 +4414,11 @@ function trimScheduleUrlProse(raw) {}// The one http(s) address a task's prompt names, so "check https://example.com/-// every day" targets that page rather than whatever tab is open.+// every day" targets that page rather than whatever tab is open. As in chat+// links, curly quotes, guillemets and CJK punctuation end the address.function scheduleUrlFromPrompt(prompt) {const urls = new Set();- for (const match of String(prompt || '').matchAll(/https?:\/\/[^\s<>"'`]+/gi)) {+ for (const match of String(prompt || '').matchAll(/https?:\/\/[^\s<>"'`“”‘’„‚«»‹›「」『』【】〔〕〈〉《》()[]{}、。,;:!?]+/gi)) {const url = trimScheduleUrlProse(match[0]);if (isHttpScheduleUrl(url)) urls.add(url);}diff --git a/src/chrome/styles/sidepanel.css b/src/chrome/styles/sidepanel.cssindex e25506193..406d90e6a 100644--- a/src/chrome/styles/sidepanel.css+++ b/src/chrome/styles/sidepanel.css@@ -2380,45 +2380,47 @@ html[dir="rtl"] .language-picker-menu {margin-bottom: 0;}+/* Chat links keep the surrounding text color. A dotted underline marks them+ and turns solid on hover or keyboard focus. */.message-content a {- color: var(--accent);- text-decoration: underline;+ color: inherit;+ text-decoration: underline dotted;text-underline-offset: 0.18em;overflow-wrap: anywhere;}-.message.user .message-content a {- color: inherit;+.message-content a:hover,+.message-content a:focus-visible {+ text-decoration-style: solid;}-.message-content a.chat-link::before {- content: '';- display: inline-block;- width: 14px;- height: 14px;- margin-inline-end: 0.35em;- vertical-align: -0.1em;- background-color: currentColor;- opacity: 0.75;- mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.7'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cellipse cx='12' cy='12' rx='4' ry='9'/%3E%3Cpath d='M3 12h18'/%3E%3C/svg%3E") center / contain no-repeat;+.message-content a:focus-visible {+ outline: 2px solid currentColor;+ outline-offset: 2px;+ border-radius: 2px;}-.message-content a.chat-link-icon-ready::before {- display: none;+/* The favicon sits in the link's start padding. An inline icon box would add a+ line break opportunity before the URL, leaving the icon alone on a line. The+ space is held while the icon loads and given back when it cannot load. */+.message-content a.chat-link:not(.chat-link-no-icon) {+ position: relative;+ padding-inline-start: calc(14px + 0.35em);}.message-content .chat-link-icon {display: none;+ position: absolute;+ inset-inline-start: 0;+ top: calc(0.6em - 7px);width: 14px;height: 14px;- margin-inline-end: 0.35em;- vertical-align: -0.1em;object-fit: contain;border-radius: 3px;}.message-content .chat-link-icon-ready > .chat-link-icon {- display: inline-block;+ display: block;}.hint {diff --git a/src/firefox/src/ui/markdown-link.js b/src/firefox/src/ui/markdown-link.jsindex b8481f26c..e7e2e5dc9 100644--- a/src/firefox/src/ui/markdown-link.js+++ b/src/firefox/src/ui/markdown-link.js@@ -29,6 +29,12 @@ const SAFE_SCHEMES = new Set(['http', 'https', 'mailto']);const MD_LINK_RE = /\[([^\]]+)\]\(((?:[^()]|\([^()]*\))*)\)/g;+// A bare URL ends at whitespace, markup, an escaped quote, or punctuation that+// only closes prose. Curly quotes, guillemets and CJK punctuation appear+// percent-encoded in real URLs; inside a host they would be IDN-encoded, so+// “https://example.com” must not link to example.xn--com-….+const PLAIN_URL_RE = /\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`“”‘’„‚«»‹›「」『』【】〔〕〈〉《》()[]{}、。,;:!?])+/gi;+/*** Sanitize a single markdown link. Returns either a safe <a> string or* the bare label text when the URL is unsafe / unrecognized.@@ -121,7 +127,7 @@ export function linkifyPlainUrls(html, precedingText = '') {return token;}if (protectedDepth) return token;- return token.replace(/\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`])+/gi, (candidate, offset, source) => {+ return token.replace(PLAIN_URL_RE, (candidate, offset, source) => {const absoluteOffset = precedingText.length + tokenOffset + offset;if (imageRanges.some(([start, end]) => absoluteOffset >= start && absoluteOffset < end)) return candidate;// Do not turn a URL embedded in another scheme or word into a new link.@@ -143,7 +149,7 @@ export function linkifyPlainUrls(html, precedingText = '') {continue;}if (last === ';' && /&(?:amp|#\d+|#x[\da-f]+);$/i.test(candidate.slice(0, end))) break;- if (/[.,!?;:]/.test(last)) { end--; continue; }+ if (/[.,!?;:…]/.test(last)) { end--; continue; }const opening = pairs[last];if (opening && balance[opening] < 0) { balance[opening]++; end--; continue; }break;diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.jsindex 4ebb03631..54ab3e2c3 100644--- a/src/firefox/src/ui/sidepanel.js+++ b/src/firefox/src/ui/sidepanel.js@@ -4269,7 +4269,7 @@ function trimScheduleUrlProse(raw) {for (;;) {const last = url.slice(-1);const opener = last === ')' ? '(' : last === ']' ? '[' : '';- if (/[.,;:!?]/.test(last) || (opener && url.split(last).length > url.split(opener).length)) {+ if (/[.,;:!?…]/.test(last) || (opener && url.split(last).length > url.split(opener).length)) {url = url.slice(0, -1);} else {return url;@@ -4278,10 +4278,11 @@ function trimScheduleUrlProse(raw) {}// The one http(s) address a task's prompt names, so "check https://example.com/-// every day" targets that page rather than whatever tab is open.+// every day" targets that page rather than whatever tab is open. As in chat+// links, curly quotes, guillemets and CJK punctuation end the address.function scheduleUrlFromPrompt(prompt) {const urls = new Set();- for (const match of String(prompt || '').matchAll(/https?:\/\/[^\s<>"'`]+/gi)) {+ for (const match of String(prompt || '').matchAll(/https?:\/\/[^\s<>"'`“”‘’„‚«»‹›「」『』【】〔〕〈〉《》()[]{}、。,;:!?]+/gi)) {const url = trimScheduleUrlProse(match[0]);if (isHttpScheduleUrl(url)) urls.add(url);}diff --git a/src/firefox/styles/sidepanel.css b/src/firefox/styles/sidepanel.cssindex fb8c44435..4d2124041 100644--- a/src/firefox/styles/sidepanel.css+++ b/src/firefox/styles/sidepanel.css@@ -2212,45 +2212,48 @@ html[dir="rtl"] .language-picker-menu {margin-bottom: 0;}+/* Chat links keep the surrounding text color. A dotted underline marks them+ and turns solid on hover or keyboard focus. */.message-content a {- color: var(--accent);- text-decoration: underline;+ color: inherit;+ text-decoration: underline dotted;text-underline-offset: 0.18em;overflow-wrap: anywhere;}-.message.user .message-content a {- color: inherit;+.message-content a:hover,+.message-content a:focus-visible {+ text-decoration-style: solid;}-.message-content a.chat-link::before {- content: '';- display: inline-block;- width: 14px;- height: 14px;- margin-inline-end: 0.35em;- vertical-align: -0.1em;- background-color: currentColor;- opacity: 0.75;- mask: url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='none' stroke='black' stroke-width='1.7'%3E%3Ccircle cx='12' cy='12' r='9'/%3E%3Cellipse cx='12' cy='12' rx='4' ry='9'/%3E%3Cpath d='M3 12h18'/%3E%3C/svg%3E") center / contain no-repeat;+.message-content a:focus-visible {+ outline: 2px solid currentColor;+ outline-offset: 2px;+ border-radius: 2px;}-.message-content a.chat-link-icon-ready::before {- display: none;++/* The favicon sits in the link's start padding. An inline icon box would add a+ line break opportunity before the URL, leaving the icon alone on a line. The+ space is held while the icon loads and given back when it cannot load. */+.message-content a.chat-link:not(.chat-link-no-icon) {+ position: relative;+ padding-inline-start: calc(14px + 0.35em);}.message-content .chat-link-icon {display: none;+ position: absolute;+ inset-inline-start: 0;+ top: calc(0.6em - 7px);width: 14px;height: 14px;- margin-inline-end: 0.35em;- vertical-align: -0.1em;object-fit: contain;border-radius: 3px;}.message-content .chat-link-icon-ready > .chat-link-icon {- display: inline-block;+ display: block;}.hint {diff --git a/test/chat-links.mjs b/test/chat-links.mjsindex 8f5264ec0..fc58b05d7 100644--- a/test/chat-links.mjs+++ b/test/chat-links.mjs@@ -54,6 +54,45 @@ for (const build of ['chrome', 'firefox']) {assert.match(html, /help<\/a>!/);});+ test(`${build}: closing quotes and prose punctuation never become part of a plain URL`, () => {+ const post = '“Introducing WebBrain — an open-source AI browser agent that lives in your browser. Try it: https://webbrain.one”\n\nVerified post URL: https://x.com/EmreSokullu/status/2114988545588736396';+ const escapeText = text => text.replace(/[&<>"']/g, character => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ })[character]);+ // Live replies, saved chat, and restored DOM text each escape quotes differently.+ for (const render of [formatMarkdown, renderSkillMarkdown, text => links.linkifyPlainUrls(escapeText(text))]) {+ const html = render(post);+ assert.deepEqual(hrefs(html), ['https://webbrain.one', 'https://x.com/EmreSokullu/status/2114988545588736396']);+ assert.equal(new URL(hrefs(html)[0]).hostname, 'webbrain.one');+ assert.match(html, /webbrain\.one<\/a>”/);+ for (const closer of ['”', '’', '»', '›', '」', '』', ')', ']', '}', '.', ',', ';', ':', '!', '?', '…', '"', "'"]) {+ for (const after of ['', ' next']) {+ const source = `Open https://example.com/path${closer}${after}`;+ assert.deepEqual(hrefs(render(source)), ['https://example.com/path'], JSON.stringify(source));+ }+ }+ for (const [open, close] of [['“', '”'], ['‘', '’'], ['«', '»'], ['»', '«'], ['‹', '›'], ['„', '“'], ['「', '」'], ['『', '』'], ['(', ')'], ['"', '"'], ["'", "'"]]) {+ const source = `${open}https://example.com/path${close}を参照。`;+ assert.deepEqual(hrefs(render(source)), ['https://example.com/path'], JSON.stringify(source));+ }+ for (const source of [+ '“https://en.wikipedia.org/wiki/Python_(programming_language)”.',+ '(see https://en.wikipedia.org/wiki/Python_(programming_language)).',+ '«https://en.wikipedia.org/wiki/Python_(programming_language)»',+ ]) {+ assert.deepEqual(hrefs(render(source)), ['https://en.wikipedia.org/wiki/Python_(programming_language)'], JSON.stringify(source));+ }+ }+ });++ test(`${build}: quoted Markdown links end at their own closing parenthesis`, () => {+ for (const render of [formatMarkdown, renderSkillMarkdown]) {+ const html = render('“[Try WebBrain](https://webbrain.one)” and “[Python](https://en.wikipedia.org/wiki/Python_(programming_language))”.');+ assert.deepEqual(hrefs(html), ['https://webbrain.one', 'https://en.wikipedia.org/wiki/Python_(programming_language)']);+ assert.match(html, /Try WebBrain<\/a>”/);+ }+ });+test(`${build}: angle-bracket links preserve escaped surrounding text`, () => {const html = formatMarkdown('See <https://example.com/path>.');assert.deepEqual(hrefs(html), ['https://example.com/path']);@@ -566,4 +605,112 @@ for (const build of ['chrome', 'firefox']) {await browser.close();}});++ if (process.env.WEBBRAIN_CHAT_LINKS_DOM === '1') test(`${build}: link icons stay on the line where a wrapped link starts`, async () => {+ const { chromium, firefox } = await import('playwright');+ const browser = await (build === 'chrome' ? chromium : firefox).launch({ headless: true });+ try {+ // The reported side panel was too narrow for the post URL after its label.+ const page = await browser.newPage({ viewport: { width: 380, height: 600 } });+ await page.route('**/*', async route => {+ const file = new URL(route.request().url()).pathname.slice(1);+ if (/^[\w-]+\.js$/.test(file)) await route.fulfill({ contentType: 'text/javascript', body: readUi(build, file) });+ else await route.fulfill({ contentType: 'text/html', body: '<html data-theme="light"><body><div id="messages" style="width: 340px"><div class="message assistant"><div class="message-content"><div id="chat-test-content" class="message-text"></div></div></div></div></body></html>' });+ });+ await page.goto('http://chat-links.test/');+ await page.addStyleTag({ content: fs.readFileSync(new URL(`../src/${build}/styles/sidepanel.css`, import.meta.url), 'utf8') });+ await page.evaluate(async ({ formatter }) => {+ const helpers = await import('/markdown-render.js');+ const links = await import('/markdown-link.js');+ const { escapeHtml } = await import('/utils.js');+ const { installChatLinkIcons } = await import('/chat-link-icons.js');+ const dependencies = { ...helpers, ...links, escapeHtml, t: key => key, scheduleMathRender() {} };+ const format = new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies));+ // x.com gets a favicon image; the other hosts keep the CSS globe.+ document.querySelector('#chat-test-content').innerHTML = format([+ 'Verified post URL: https://x.com/EmreSokullu/status/2114988545588736396',+ 'Try it: https://webbrain.one',+ 'Fallback icon URL: https://twitter.com/EmreSokullu/status/2114988545588736396',+ ].join('\n\n'), { enhance: false });+ const canvas = document.createElement('canvas');+ canvas.width = 14; canvas.height = 14;+ canvas.getContext('2d').fillRect(0, 0, 14, 14);+ const png = Uint8Array.from(atob(canvas.toDataURL('image/png').split(',')[1]), char => char.charCodeAt(0));+ installChatLinkIcons(document.querySelector('#messages'), {+ intersectionObserverImpl: null,+ fetchImpl: async url => String(url).endsWith('/x.com.ico')+ ? new Response(png, { headers: { 'content-type': 'image/png' } })+ : new Response('', { status: 404 }),+ });+ }, { formatter: formatterSource(build) });+ await page.waitForFunction(() => document.querySelector('#chat-test-content a.chat-link-icon-ready > img')?.complete);+ const layout = await page.evaluate(() => {+ const box = ({ left, right, top, bottom }) => ({ left, right, top, bottom });+ const content = box(document.querySelector('#chat-test-content').getBoundingClientRect());+ return [...document.querySelectorAll('#chat-test-content a')].map(link => {+ const firstCharacter = document.createRange();+ firstCharacter.setStart(document.createTreeWalker(link, NodeFilter.SHOW_TEXT).nextNode(), 0);+ firstCharacter.setEnd(firstCharacter.startContainer, 1);+ const label = document.createRange();+ label.selectNodeContents(link.previousSibling);+ const icon = link.classList.contains('chat-link-icon-ready') ? link.querySelector('img.chat-link-icon') : null;+ return {+ href: link.href,+ content,+ fragments: [...link.getClientRects()].map(box),+ firstCharacter: box(firstCharacter.getBoundingClientRect()),+ label: box([...label.getClientRects()].at(-1)),+ icon: icon && box(icon.getBoundingClientRect()),+ fallbackIcon: icon ? null : getComputedStyle(link, '::before').position,+ };+ });+ });+ const sameLine = (a, b) => a.top < b.bottom && b.top < a.bottom;+ assert.equal(layout.length, 3);+ for (const link of layout) {+ const [first] = link.fragments;+ assert.ok(sameLine(first, link.firstCharacter), `${link.href}: the link's first line holds its first character`);+ assert.ok(link.firstCharacter.left - first.left >= 14, `${link.href}: icon space precedes the first character`);+ for (const fragment of link.fragments) {+ assert.ok(fragment.left >= link.content.left - 1 && fragment.right <= link.content.right + 1, `${link.href}: no overflow`);+ }+ if (link.icon) {+ assert.ok(sameLine(link.icon, link.firstCharacter), `${link.href}: favicon shares the first line`);+ assert.ok(Math.abs(link.icon.left - first.left) <= 1 && link.icon.right <= link.firstCharacter.left, `${link.href}: favicon leads the link`);+ } else {+ assert.equal(link.fallbackIcon, 'absolute', `${link.href}: the CSS icon is drawn in the reserved space`);+ }+ }+ const [post, tryIt, fallback] = layout;+ assert.ok(post.icon, 'the x.com link uses its favicon image');+ assert.ok(post.fragments.length > 1 && fallback.fragments.length > 1, 'long post URLs wrap inside the panel');+ assert.equal(tryIt.fragments.length, 1);+ assert.ok(sameLine(tryIt.label, tryIt.fragments[0]), '"Try it:" and its short link share one line');++ // Links keep the text color; a dotted underline turns solid on hover and focus.+ const linkStyle = () => page.evaluate(() => {+ const link = document.querySelector('#chat-test-content a');+ const style = getComputedStyle(link);+ return {+ color: style.color,+ textColor: getComputedStyle(link.parentElement).color,+ underline: style.textDecorationStyle,+ outline: `${style.outlineStyle} ${style.outlineWidth}`,+ };+ });+ const idle = await linkStyle();+ assert.equal(idle.color, idle.textColor);+ assert.equal(idle.underline, 'dotted');+ await page.hover('#chat-test-content a');+ assert.equal((await linkStyle()).underline, 'solid');+ await page.mouse.move(0, 0);+ await page.keyboard.press('Shift');+ await page.focus('#chat-test-content a');+ const focused = await linkStyle();+ assert.equal(focused.underline, 'solid');+ assert.equal(focused.outline, 'solid 2px');+ } finally {+ await browser.close();+ }+ });}diff --git a/test/run.js b/test/run.jsindex bcf6dc51f..62cf7d479 100644--- a/test/run.js+++ b/test/run.js@@ -42876,6 +42876,13 @@ test('sidepanel exposes schedule slash commands in both builds', () => {assert.equal(pick('See https://en.wikipedia.org/wiki/Function_(mathematics) daily.'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: a bracket that closes one inside the address stays`);assert.equal(pick('(see https://en.wikipedia.org/wiki/Function_(mathematics)).'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: prose punctuation after a balanced address is dropped`);assert.equal(pick('Check [https://example.com/a].'), 'https://example.com/a');+ assert.equal(pick('Check “https://webbrain.one” daily.'), 'https://webbrain.one', `${label}: a closing curly quote never reaches the host`);+ for (const [open, close] of [['“', '”'], ['‘', '’'], ['«', '»'], ['»', '«'], ['„', '“'], ['「', '」'], ['『', '』'], ['(', ')']]) {+ assert.equal(pick(`毎日${open}https://example.com/a${close}を確認。`), 'https://example.com/a', `${label}: ${open}…${close} stays outside the address`);+ }+ assert.equal(pick('Check https://example.com/a。次に報告'), 'https://example.com/a', `${label}: CJK punctuation ends the address`);+ assert.equal(pick('Check https://example.com/a…'), 'https://example.com/a');+ assert.equal(pick('Check “https://en.wikipedia.org/wiki/Function_(mathematics)”.'), 'https://en.wikipedia.org/wiki/Function_(mathematics)', `${label}: balanced brackets survive inside quotes`);}assert.match(panel, /targetType\.value = 'url'/, `${label}: schedule form should default http(s) pages to URL targets`);assert.match(panel, /content\.appendChild\(form\)/, `${label}: schedule form should append after initial target defaults are applied`);