Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Add safe chat links and favicons in both browsers

Codex release-state test22fc12a0ad89
diff --git a/docs/privacy-and-data-flow.md b/docs/privacy-and-data-flow.md
index ec5c6a0e2..93d4193b0 100644
--- a/docs/privacy-and-data-flow.md
+++ b/docs/privacy-and-data-flow.md
@@ -619,7 +619,14 @@ The only outbound HTTP requests are:
7. **Encrypted Cloud Sync calls** to `https://api.webbrain.one/v1/sync` (only after a subscriber explicitly enables sync; vault content is encrypted before upload)
8. **Slash-driven tab/screen recording** creates no outbound traffic (the .webm is saved to the Downloads folder via `chrome.downloads.download`)
9. **Voluntary research shares** to `https://api.webbrain.one/v1/improvement/generations` and `/v1/improvement/diagnostic-traces` (only for a local or bring-your-own provider with its separate sharing switch enabled)
-10. **Feedback trace attachments** uploaded by GitHub's native issue editor,
+10. **Chat link favicons** use `https://icons.duckduckgo.com/ip3/` for public
+ website hostnames visible in the chat. The lookup sends only the hostname,
+ never the link's path, query string, fragment, credentials or a referrer.
+ Icons are cached in memory while the panel is open, with bounded requests
+ and response sizes. Local hosts, IP addresses, code, Markdown image syntax
+ and download links do not trigger these requests. Strict Secret Mode disables
+ remote icon lookups; unavailable icons use a local globe.
+11. **Feedback trace attachments** uploaded by GitHub's native issue editor,
only after the user chooses **Upload trace and open GitHub** in the extension.
Preparing, viewing, and downloading the trace are local operations. The
attachment includes only recordings preceding the opening of the rating
@@ -634,7 +641,7 @@ The only outbound HTTP requests are:
same authorized bytes. Full traces that exceed the attachment limit use an
explicitly disclosed diagnostic fallback; the original stays available as
a local download.
-11. **WebBrain bulletins**: a `GET` of a fixed static file on `https://webbrain.one`, with no
+12. **WebBrain bulletins**: a `GET` of a fixed static file on `https://webbrain.one`, with no
cookies, referrer, query string or identifiers. The new tab page reads
`/newtab-comm.html` at most once every 10 minutes per browser (only while the new tab is
shown); Apocalypse Mode pages read `/apocalypse-comm.html` when they open. Both files ship
diff --git a/docs/prompt-injection-defense.md b/docs/prompt-injection-defense.md
index 0240eabd6..98c811a4b 100644
--- a/docs/prompt-injection-defense.md
+++ b/docs/prompt-injection-defense.md
@@ -41,10 +41,18 @@ them in sync — the test suite asserts the pure modules are byte-identical.
switch "Ask before consequential actions"). The warning button in the side panel's
composer toolbar toggles the same master switch; it never answers a pending
permission card.
-4. **Output sanitizer (Layer 4).** Model output is HTML-escaped and only
- `[label](url)` markdown becomes an allowlisted (http/https/mailto) link — no
- auto-loading images, no bare-URL linkification.
- - Code: `ui/markdown-link.js`.
+4. **Output sanitizer (Layer 4).** Model output is HTML-escaped. Markdown links
+ use an http/https/mailto allowlist; plain HTTP(S) URLs become links outside
+ code and existing anchors. Links open a new tab with `noopener noreferrer`.
+ Formatter placeholders use a source-collision-free namespace and are restored
+ in one pass, so source text cannot expand into generated HTML attributes.
+ Markdown images, including unfinished streaming syntax, never load an image
+ or trigger a favicon lookup. Chat link
+ icons come only from a fixed favicon service using a validated public
+ hostname, without URL paths, query strings, credentials or a referrer.
+ Responses are bounded raster images rendered through local blob URLs;
+ failed lookups keep a local globe icon.
+ - Code: `ui/markdown-link.js`, `ui/markdown-render.js`, `ui/chat-link-icons.js`.
---
diff --git a/package.json b/package.json
index bf1941fea..5f26099f2 100644
--- a/package.json
+++ b/package.json
@@ -24,7 +24,8 @@
"test:provider-instances:ui": "node test/provider-instances-ui.mjs",
"test:settings-pages:ui": "node test/settings-pages-ui.mjs",
"test:openrouter-capabilities": "node --test test/frontier-model-compatibility.mjs test/openrouter-model-capabilities.mjs test/muse-tool-choice.mjs test/qwen-tool-calls.mjs test/dolphin-prompted-tools.mjs test/model-retry.mjs",
- "test:markdown": "node --test test/markdown-render.mjs",
+ "test:markdown": "node --test test/markdown-render.mjs test/chat-links.mjs",
+ "test:markdown:ui": "WEBBRAIN_MARKDOWN_DOM=1 WEBBRAIN_CHAT_LINKS_DOM=1 node --test test/markdown-render.mjs test/chat-links.mjs",
"test:accessibility-tree-benchmark": "node --test test/llm/lib/accessibility-tree-formats.test.mjs test/llm/report-html-encoding.mjs && node test/llm/accessibility-tree-benchmark.mjs --no-exact-tokenizer --check",
"test:attachment-drop": "node test/attachment-drop.mjs",
"test:workflow-editor": "node --test test/workflow-editor.mjs",
diff --git a/src/chrome/src/ui/chat-link-icons.js b/src/chrome/src/ui/chat-link-icons.js
new file mode 100644
index 000000000..e22e76cdc
--- /dev/null
+++ b/src/chrome/src/ui/chat-link-icons.js
@@ -0,0 +1,322 @@
+import { linkifyPlainUrls, markdownImageRanges } from './markdown-link.js';
+
+const ICON_SERVICE = 'https://icons.duckduckgo.com/ip3/';
+const MAX_ICON_BYTES = 64 * 1024;
+const RASTER_TYPES = new Set(['image/x-icon', 'image/vnd.microsoft.icon', 'image/ico', 'image/icon', 'image/png', 'image/jpeg', 'image/webp']);
+const CHAT_TEXT_SELECTOR = '.message-text, .slash-command-text';
+const LINKIFY_SKIP_SELECTOR = 'a, pre, code, style, script, button, textarea, [data-no-favicon]';
+const LOCAL_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'lan', 'home', 'corp', 'private', 'test', 'invalid', 'example', 'onion', 'arpa'];
+
+function publicHostname(href, baseURI) {
+ try {
+ const url = new URL(href, baseURI);
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
+ const hostname = url.hostname.toLowerCase().replace(/\.$/, '');
+ if (hostname.length > 253 || !hostname.includes('.') || /[:\[\]]/.test(hostname)
+ || /^[\d.]+$/.test(hostname) || LOCAL_SUFFIXES.some(suffix => hostname === suffix || hostname.endsWith(`.${suffix}`))) return '';
+ const labels = hostname.split('.');
+ if (!labels.every(label => /^[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?$/.test(label))
+ || !/^(?:[a-z]{2,63}|xn--[a-z\d-]+)$/.test(labels.at(-1))) return '';
+ return hostname;
+ } catch { return ''; }
+}
+
+function rasterSignature(bytes, mime) {
+ if (mime === 'image/png') return [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value);
+ if (mime === 'image/jpeg') return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
+ if (mime === 'image/webp') return String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
+ && String.fromCharCode(...bytes.slice(8, 12)) === 'WEBP';
+ return bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0;
+}
+
+async function readIcon(response) {
+ if (!response.ok) {
+ await response.body?.cancel?.().catch(() => {});
+ throw new Error('Favicon unavailable');
+ }
+ const mime = String(response.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
+ const size = Number(response.headers.get('content-length'));
+ if (!RASTER_TYPES.has(mime) || size > MAX_ICON_BYTES || !response.body?.getReader) {
+ await response.body?.cancel?.().catch(() => {});
+ throw new Error('Unsupported favicon');
+ }
+ const reader = response.body.getReader();
+ const chunks = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_ICON_BYTES) throw new Error('Favicon too large');
+ chunks.push(value);
+ }
+ } catch (error) {
+ await reader.cancel().catch(() => {});
+ throw error;
+ } finally { reader.releaseLock(); }
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
+ if (!rasterSignature(bytes, mime)) throw new Error('Invalid favicon');
+ return new Blob([bytes], { type: mime });
+}
+
+/**
+ * Decorate chat links without allowing model text to choose an image URL.
+ * Only a public hostname reaches the fixed favicon service; paths, queries,
+ * fragments, cookies and referrers are never sent. Failures retain the CSS icon.
+ * The returned function releases observers, requests and local image URLs.
+ */
+export function installChatLinkIcons(root, {
+ fetchImpl = globalThis.fetch,
+ timeoutMs = 5000,
+ maxDomains = 64,
+ concurrency = 4,
+ observerImpl = root?.ownerDocument?.defaultView?.MutationObserver ?? globalThis.MutationObserver,
+ intersectionObserverImpl = root?.ownerDocument?.defaultView?.IntersectionObserver ?? globalThis.IntersectionObserver,
+} = {}) {
+ if (!root?.querySelectorAll) return () => {};
+ const document = root.ownerDocument;
+ const cacheLimit = Math.min(64, Math.max(1, Math.floor(Number(maxDomains) || 64)));
+ const workerLimit = Math.min(4, Math.max(1, Math.floor(Number(concurrency) || 4)));
+ const deadline = Math.min(10000, Math.max(1, Number(timeoutMs) || 5000));
+ const entries = new Map();
+ const decorated = new WeakMap();
+ const inspectedText = new WeakMap();
+ const queue = [];
+ const controllers = new Set();
+ const objectUrls = new Set();
+ const added = new Set();
+ let disposed = false;
+ let scheduled = false;
+ let running = 0;
+
+ function stillCurrent(image, entry) {
+ const link = image.parentElement;
+ return !disposed && root.contains(image) && decorated.get(link)?.image === image
+ && decorated.get(link)?.hostname === entry.hostname;
+ }
+
+ function applyImage(image, entry) {
+ if (!entry.url || !stillCurrent(image, entry)) return;
+ image.onload = () => {
+ if (stillCurrent(image, entry)) image.parentElement.classList.add('chat-link-icon-ready');
+ };
+ image.onerror = () => {
+ if (stillCurrent(image, entry)) image.parentElement.classList.remove('chat-link-icon-ready');
+ image.removeAttribute('src');
+ };
+ image.src = entry.url;
+ }
+
+ async function load(entry) {
+ const controller = new AbortController();
+ controllers.add(controller);
+ let timer;
+ try {
+ const timeout = new Promise((_, reject) => {
+ controller.signal.addEventListener('abort', () => reject(new Error('Favicon request cancelled')), { once: true });
+ timer = setTimeout(() => controller.abort(), deadline);
+ });
+ const result = await Promise.race([
+ Promise.resolve().then(() => {
+ if (controller.signal.aborted) throw new Error('Favicon request cancelled');
+ return fetchImpl(`${ICON_SERVICE}${encodeURIComponent(entry.hostname)}.ico`, {
+ credentials: 'omit', referrerPolicy: 'no-referrer', redirect: 'error', signal: controller.signal,
+ });
+ }).then(readIcon),
+ timeout,
+ ]);
+ if (disposed) return;
+ entry.url = URL.createObjectURL(result);
+ objectUrls.add(entry.url);
+ entry.status = 'ready';
+ for (const image of entry.images) applyImage(image, entry);
+ } catch {
+ entry.status = 'failed';
+ } finally {
+ clearTimeout(timer);
+ controllers.delete(controller);
+ entry.images.clear();
+ running--;
+ pump();
+ }
+ }
+
+ function pump() {
+ while (!disposed && running < workerLimit && queue.length) {
+ const entry = queue.shift();
+ running++;
+ entry.status = 'loading';
+ void load(entry);
+ }
+ }
+
+ function requestIcon(link) {
+ const state = decorated.get(link);
+ if (disposed || !state?.image || !root.contains(link)) return;
+ let entry = entries.get(state.hostname);
+ if (!entry) {
+ // A hard per-panel bound prevents long chats or streamed replacements
+ // from causing unbounded lookups or an eviction/re-fetch loop.
+ if (entries.size >= cacheLimit || typeof fetchImpl !== 'function') return;
+ entry = { hostname: state.hostname, status: 'queued', url: '', images: new Set() };
+ entries.set(state.hostname, entry);
+ queue.push(entry);
+ }
+ if (entry.status === 'ready') applyImage(state.image, entry);
+ else if (entry.status !== 'failed') {
+ for (const image of entry.images) if (!stillCurrent(image, entry)) entry.images.delete(image);
+ entry.images.add(state.image);
+ }
+ pump();
+ }
+
+ const visibility = typeof intersectionObserverImpl === 'function' ? new intersectionObserverImpl(records => {
+ for (const record of records) if (record.isIntersecting) {
+ visibility.unobserve(record.target);
+ requestIcon(record.target);
+ }
+ }) : null;
+
+ function precedingChatText(node) {
+ const parent = node.nodeType === 1 ? node : node.parentElement;
+ const message = parent?.closest(CHAT_TEXT_SELECTOR);
+ if (!message || message === node) return '';
+ const walker = document.createTreeWalker(message, 5, {
+ acceptNode: child => child.nodeType === 1
+ ? (child.matches('pre, code, style, script, button, textarea') ? 2 : 1) : 1,
+ });
+ let text = '';
+ while (walker.nextNode() && walker.currentNode !== node) {
+ if (walker.currentNode.nodeType === 3) text += walker.currentNode.textContent;
+ }
+ return text;
+ }
+
+ function decorate(link) {
+ if (!root.contains(link)) return;
+ const href = link.getAttribute('href');
+ // Older saved HTML can contain !<a>, or an auto-link inside unfinished image
+ // syntax. Include earlier inline siblings so formatting cannot hide it.
+ if (!link.hasAttribute('data-no-favicon')) {
+ const prefix = precedingChatText(link);
+ if (prefix.endsWith('!') || markdownImageRanges(prefix + link.textContent)
+ .some(([start, end]) => start < prefix.length && end > prefix.length)) {
+ link.setAttribute('data-no-favicon', 'true');
+ }
+ }
+ if (href !== null) {
+ link.target = '_blank';
+ const rel = new Set(String(link.getAttribute('rel') || '').split(/\s+/).filter(Boolean));
+ rel.add('noopener'); rel.add('noreferrer');
+ link.setAttribute('rel', [...rel].join(' '));
+ }
+ const hostname = href !== null && !link.hasAttribute('download') && !link.closest('pre, code, [data-no-favicon]')
+ ? publicHostname(href, document.baseURI) : '';
+ const previous = decorated.get(link);
+ if (previous?.hostname === hostname && previous?.href === href) return;
+ visibility?.unobserve(link);
+ if (previous?.image) entries.get(previous.hostname)?.images.delete(previous.image);
+ previous?.image?.remove();
+ // Restored chat HTML may contain an object URL from a closed panel.
+ for (const image of link.querySelectorAll('.chat-link-icon')) image.remove();
+ link.classList.remove('chat-link-icon-ready');
+ link.classList.toggle('chat-link', Boolean(hostname));
+ const state = { href, hostname, image: null };
+ decorated.set(link, state);
+ if (!hostname) return;
+ const image = document.createElement('img');
+ image.className = 'chat-link-icon';
+ image.alt = '';
+ image.setAttribute('aria-hidden', 'true');
+ image.width = 14; image.height = 14;
+ image.decoding = 'async';
+ image.referrerPolicy = 'no-referrer';
+ state.image = image;
+ link.prepend(image);
+ if (visibility) visibility.observe(link);
+ else requestIcon(link);
+ }
+
+ function linkifyTextNode(node) {
+ const parent = node.parentElement;
+ if (!parent?.closest(CHAT_TEXT_SELECTOR) || parent.closest(LINKIFY_SKIP_SELECTOR)) return;
+ const text = node.textContent;
+ if (inspectedText.get(node) === text) return;
+ inspectedText.set(node, text);
+ if (!/https?:\/\//i.test(text)) return;
+ const escaped = text.replace(/[&<>"']/g, character => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[character]);
+ const html = linkifyPlainUrls(escaped, precedingChatText(node));
+ if (!html.includes('<a ')) return;
+ const template = document.createElement('template');
+ template.innerHTML = html;
+ const links = [...template.content.querySelectorAll('a')];
+ node.replaceWith(template.content);
+ for (const link of links) decorate(link);
+ }
+
+ function scan(node) {
+ if (node.nodeType === 3) { linkifyTextNode(node); return; }
+ if (node.nodeType !== 1) return;
+ if (node.matches('a')) decorate(node);
+ for (const link of node.querySelectorAll('a[href]')) decorate(link);
+ // Saved chat HTML predates the formatter change. Upgrade only the newly
+ // restored subtree, never code or existing links, without rerendering it.
+ const walker = document.createTreeWalker(node, 5, {
+ acceptNode: child => child.nodeType === 1 ? (child.matches(LINKIFY_SKIP_SELECTOR) ? 2 : 3) : 1,
+ });
+ const textNodes = [];
+ while (walker.nextNode()) textNodes.push(walker.currentNode);
+ for (const text of textNodes) linkifyTextNode(text);
+ }
+
+ function detach(node) {
+ if (node.nodeType !== 1 || root.contains(node)) return;
+ const links = [...(node.matches('a') ? [node] : []), ...node.querySelectorAll('a')];
+ for (const link of links) {
+ visibility?.unobserve(link);
+ const state = decorated.get(link);
+ if (state?.image) entries.get(state.hostname)?.images.delete(state.image);
+ decorated.delete(link);
+ }
+ }
+
+ const observer = typeof observerImpl === 'function' ? new observerImpl(records => {
+ for (const record of records) {
+ if (record.type === 'attributes' || record.type === 'characterData') added.add(record.target);
+ else {
+ for (const node of record.removedNodes) detach(node);
+ for (const node of record.addedNodes) if (node.nodeType === 1 || node.nodeType === 3) added.add(node);
+ }
+ }
+ if (scheduled || !added.size) return;
+ scheduled = true;
+ queueMicrotask(() => {
+ scheduled = false;
+ if (disposed) return;
+ const nodes = new Set(added); added.clear();
+ for (const node of nodes) {
+ if (!root.contains(node)) continue;
+ let parent = node.parentNode;
+ while (parent && !nodes.has(parent)) parent = parent.parentNode;
+ if (!parent) scan(node);
+ }
+ });
+ }) : null;
+ scan(root);
+ observer?.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['href', 'data-no-favicon', 'download'] });
+
+ return () => {
+ disposed = true;
+ observer?.disconnect(); visibility?.disconnect();
+ added.clear(); queue.length = 0;
+ for (const controller of controllers) controller.abort();
+ controllers.clear();
+ for (const url of objectUrls) URL.revokeObjectURL(url);
+ objectUrls.clear(); entries.clear();
+ };
+}
diff --git a/src/chrome/src/ui/markdown-link.js b/src/chrome/src/ui/markdown-link.js
index faa9716e8..b8481f26c 100644
--- a/src/chrome/src/ui/markdown-link.js
+++ b/src/chrome/src/ui/markdown-link.js
@@ -55,5 +55,105 @@ export function sanitizeLink(label, href) {
* sanitizeLink. Non-link text is passed through unchanged.
*/
export function sanitizeMarkdownLinks(text) {
- return String(text == null ? '' : text).replace(MD_LINK_RE, (_m, label, href) => sanitizeLink(label, href));
+ return String(text == null ? '' : text).replace(MD_LINK_RE, (_m, label, href, offset, source) => {
+ const link = sanitizeLink(label, href);
+ // Markdown images stay links, without even an indirect favicon request.
+ if (source[offset - 1] !== '!') return link;
+ return link.startsWith('<a ') ? link.replace(/^<a /, '<a data-no-favicon="true" ')
+ : `<span data-no-favicon="true">${label}</span>`;
+ });
+}
+
+// Image syntax is inert even before streaming has supplied its closing bracket
+// or parenthesis. Track balanced delimiters instead of assuming a URL following
+// an unfinished image is ordinary prose. Ranges include labels as well as URLs.
+export function markdownImageRanges(text) {
+ const source = String(text ?? '');
+ const ranges = [];
+ let cursor = 0;
+ const balancedEnd = (start, open, close) => {
+ let depth = 1;
+ for (let index = start + 1; index < source.length; index++) {
+ if (source[index] === '\\') { index++; continue; }
+ if (source[index] === open) depth++;
+ else if (source[index] === close && --depth === 0) return index + 1;
+ }
+ return source.length;
+ };
+ while ((cursor = source.indexOf('![', cursor)) !== -1) {
+ const start = cursor;
+ let end = balancedEnd(cursor + 1, '[', ']');
+ if (source[end] === '(') end = balancedEnd(end, '(', ')');
+ else if (source[end] === '[') end = balancedEnd(end, '[', ']');
+ ranges.push([start, end]);
+ cursor = Math.max(end, start + 2);
+ }
+ return ranges;
+}
+
+// Input is already HTML-escaped, with fixed Markdown markup added. Only text
+// nodes are linkified: existing anchors, code and generated attributes stay intact.
+export function linkifyPlainUrls(html, precedingText = '') {
+ const source = String(html ?? '');
+ const protectedTags = new Set(['a', 'code', 'pre']);
+ let protectedDepth = 0;
+ // Ignore generated tags while retaining offsets and syntax across inline
+ // formatting. Literal code or existing links cannot start image syntax in
+ // adjacent prose. Restored DOM text supplies earlier siblings as context.
+ const imageContext = source.replace(/<[^>]*>|[^<]+|</g, token => {
+ if (token.startsWith('<')) {
+ const tag = /^<(\/?)([a-z][\w-]*)\b/i.exec(token);
+ if (tag && protectedTags.has(tag[2].toLowerCase())) {
+ protectedDepth = Math.max(0, protectedDepth + (tag[1] ? -1 : 1));
+ }
+ return ' '.repeat(token.length);
+ }
+ return protectedDepth ? ' '.repeat(token.length) : token;
+ });
+ const imageRanges = markdownImageRanges(precedingText + imageContext);
+ protectedDepth = 0;
+ return source.replace(/<[^>]*>|[^<]+|</g, (token, tokenOffset) => {
+ if (token.startsWith('<')) {
+ const tag = /^<(\/?)([a-z][\w-]*)\b/i.exec(token);
+ if (tag && protectedTags.has(tag[2].toLowerCase())) {
+ protectedDepth = Math.max(0, protectedDepth + (tag[1] ? -1 : 1));
+ }
+ return token;
+ }
+ if (protectedDepth) return token;
+ return token.replace(/\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`])+/gi, (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.
+ if (offset && /[\w@:/]/.test(source[offset - 1])) return candidate;
+ let end = candidate.length;
+ const emphasis = /(?:^|[\s(\[{>])(\*{1,3})(?=\S|$)[^*\n]*$/.exec(source.slice(0, offset))?.[1];
+ let closedEmphasis = false;
+ const pairs = { ')': '(', ']': '[', '}': '{' };
+ const balance = { '(': 0, '[': 0, '{': 0 };
+ for (const character of candidate) {
+ if (Object.hasOwn(balance, character)) balance[character]++;
+ else if (pairs[character]) balance[pairs[character]]--;
+ }
+ while (end) {
+ const last = candidate[end - 1];
+ if (!closedEmphasis && emphasis && candidate.slice(0, end).endsWith(emphasis)) {
+ end -= emphasis.length;
+ closedEmphasis = true;
+ continue;
+ }
+ if (last === ';' && /&(?:amp|#\d+|#x[\da-f]+);$/i.test(candidate.slice(0, end))) break;
+ if (/[.,!?;:]/.test(last)) { end--; continue; }
+ const opening = pairs[last];
+ if (opening && balance[opening] < 0) { balance[opening]++; end--; continue; }
+ break;
+ }
+ const href = candidate.slice(0, end);
+ try {
+ const parsed = new URL(href.replace(/&amp;/g, '&'));
+ if (!parsed.hostname || !['http:', 'https:'].includes(parsed.protocol)) return candidate;
+ } catch { return candidate; }
+ return sanitizeLink(href, href) + candidate.slice(end);
+ });
+ });
}
diff --git a/src/chrome/src/ui/markdown-render.js b/src/chrome/src/ui/markdown-render.js
index 954ac8c99..53e6410b9 100644
--- a/src/chrome/src/ui/markdown-render.js
+++ b/src/chrome/src/ui/markdown-render.js
@@ -50,6 +50,37 @@ export function escapeCodeHtml(value) {
}[character]));
}
+// Pick a namespace absent from the source, and restore only the tokens that
+// existed before this pass. Model text must never name or recursively expand
+// one of the renderer's HTML fragments.
+export function createMarkdownPlaceholders(source) {
+ const occupied = new Set([...String(source).matchAll(/WBMD(\d+)TOKEN/g)].map(match => match[1]));
+ let namespace = 0;
+ while (occupied.has(String(namespace))) namespace++;
+ const prefix = `WBMD${namespace}TOKEN`;
+ const tokenPattern = new RegExp(`${prefix}(\\d+)END`, 'g');
+ const htmlPattern = new RegExp(`<[^>]*>|${prefix}(\\d+)END`, 'g');
+ const fragments = [];
+ const restore = value => String(value).replace(htmlPattern, (match, index) => {
+ if (index !== undefined) return fragments[Number(index)]?.html ?? match;
+ // Inline code can occur inside a Markdown destination. It is attribute
+ // text there, never HTML, even when the same fragment is markup in a label.
+ return match.replace(tokenPattern, (token, id) => {
+ const fragment = fragments[Number(id)];
+ return fragment ? escapeCodeHtml(fragment.text) : token;
+ });
+ });
+ return {
+ restore,
+ add(html, text = '') {
+ const rendered = restore(html);
+ const token = `${prefix}${fragments.length}END`;
+ fragments.push({ html: rendered, text });
+ return token;
+ },
+ };
+}
+
export function normalizeCodeLanguage(language) {
return LANGUAGE_ALIASES[String(language || '').trim().toLowerCase()] || '';
}
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index 6b91aa1b2..f70f7726f 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -15,8 +15,9 @@ import { createComposerModePins } from './composer-mode-pin.js';
import { reportSidePanelPresence } from '../sidepanel-presence.js';
import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';
import { CAPABILITY_LABEL } from '../agent/permission-gate.js';
-import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
+import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';
+import { installChatLinkIcons } from './chat-link-icons.js';
+import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
import { applyMode, loadMode, watch } from './theme.js';
import {
UI_SCALE_LEVELS,
@@ -692,6 +693,14 @@ const pinCoachmarkDismissed = (async function initPinCoachmark() {
})();
const messagesEl = document.getElementById('messages');
+const disposeChatLinkIcons = installChatLinkIcons(messagesEl, {
+ fetchImpl: async (url, options) => {
+ const { strictSecretMode } = await chrome.storage.local.get('strictSecretMode');
+ if (strictSecretMode === true) throw new Error('Remote chat icons are disabled in Strict Secret Mode.');
+ return fetch(url, options);
+ },
+});
+window.addEventListener('pagehide', disposeChatLinkIcons, { once: true });
const chatContainerEl = document.getElementById('chat-container');
const chatNavigationEl = document.getElementById('chat-navigation');
const chatNavigationActionEl = document.getElementById('chat-navigation-action');
@@ -5198,6 +5207,8 @@ async function exportSavedWorkflow(id, tabId = currentTabId) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
+ link.target = '_blank';
+ link.rel = 'noopener noreferrer';
link.download = savedWorkflowDownloadFilename(res.workflow.name);
document.body.appendChild(link);
try {
@@ -9898,6 +9909,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-config-${Date.now()}.json`;
document.body.appendChild(a);
try {
@@ -9944,6 +9957,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-traces-${Date.now()}.${res.json ? 'json' : 'md'}`;
document.body.appendChild(a);
try {
@@ -9988,6 +10003,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-chat-${Date.now()}.md`;
document.body.appendChild(a);
try {
@@ -14807,21 +14824,27 @@ function formatMarkdown(text, options = {}) {
const enhance = options.enhance !== false;
const streaming = options.recoverNestedMarkdown === true;
+ const placeholders = createMarkdownPlaceholders(text);
+
// 1. Extract fenced code blocks BEFORE escaping HTML
const codeBlocks = [];
text = replaceMarkdownCodeFences(text, (info, code) => {
const lang = codeFenceLanguage(info);
- const id = `__CODEBLOCK_${codeBlocks.length}__`;
+ const index = codeBlocks.length;
codeBlocks.push({ lang: lang || '', code });
- return id;
+ const highlighted = enhance ? highlightCode(code, lang) : escapeHtml(code);
+ const langLabel = lang ? `<span class="code-lang">${escapeHtml(lang)}</span>` : '';
+ const copyBtn = enhance
+ ? `<button class="code-copy-btn" data-code-index="${index}" title="${escapeHtml(t('sp.copy.code.title'))}">${escapeHtml(t('sp.copy'))}</button>`
+ : '';
+ const header = langLabel || copyBtn ? `<div class="code-block-header">${langLabel}${copyBtn}</div>` : '';
+ return placeholders.add(`<div class="code-block-wrapper">${header}<pre><code>${highlighted}</code></pre></div>`, code);
}, { streaming });
// 2. Extract inline code before escaping
- const inlineCodes = [];
text = text.replace(/`([^`\n]+)`/g, (_match, code) => {
- const id = `__INLINE_${inlineCodes.length}__`;
- inlineCodes.push(code);
- return id;
+ const escaped = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+ return placeholders.add(`<code>${escaped}</code>`, code);
});
// 3. Escape HTML in the remaining text
@@ -14838,38 +14861,15 @@ function formatMarkdown(text, options = {}) {
text = renderMarkdownTables(text);
text = renderMarkdownBlockquotes(text);
text = renderMarkdownHeadings(text);
- text = text
+ const emphasis = value => value
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>');
- text = sanitizeMarkdownLinks(text);
- text = text.replace(/\n/g, '<br>');
-
- // 5. Restore inline code
- inlineCodes.forEach((code, i) => {
- const escaped = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
- // Function replacer: a string replacement would interpret `$&`, `$\``, etc.
- // in code that contains literal `$` sequences (shell, jQuery, regex), mangling it.
- text = text.replace(`__INLINE_${i}__`, () => `<code>${escaped}</code>`);
- });
-
- // 6. Restore fenced code blocks with copy button
- codeBlocks.forEach((block, i) => {
- // Re-highlighting every accumulated token is expensive and can visibly
- // flicker. Keep live code escaped/plain, then highlight it once when the
- // authoritative terminal response arrives.
- const highlighted = enhance ? highlightCode(block.code, block.lang) : escapeHtml(block.code);
- const langLabel = block.lang ? `<span class="code-lang">${escapeHtml(block.lang)}</span>` : '';
- const copyBtn = enhance
- ? `<button class="code-copy-btn" data-code-index="${i}" title="${escapeHtml(t('sp.copy.code.title'))}">${escapeHtml(t('sp.copy'))}</button>`
- : '';
- const header = langLabel || copyBtn
- ? `<div class="code-block-header">${langLabel}${copyBtn}</div>`
- : '';
- text = text.replace(
- `__CODEBLOCK_${i}__`,
- () => `<div class="code-block-wrapper">${header}<pre><code>${highlighted}</code></pre></div>`
- );
- });
+ // Protect destinations from emphasis (a URL can itself contain '*').
+ text = linkifyPlainUrls(sanitizeMarkdownLinks(text)).replace(/(<a\b[^>]*>)([\s\S]*?)(<\/a>)/g, (_match, open, label, close) => (
+ placeholders.add(`${open}${/^https?:\/\/\S+$/i.test(label) ? label : emphasis(label)}${close}`)
+ ));
+ text = emphasis(text).replace(/\n/g, '<br>');
+ text = placeholders.restore(text);
// Schedule KaTeX rendering of any math expressions in the messages area.
// auto-render walks text nodes and replaces $...$, $$...$$, \(...\), \[...\]
diff --git a/src/chrome/src/ui/skill-markdown.js b/src/chrome/src/ui/skill-markdown.js
index 2dd0f4ac6..004b59d09 100644
--- a/src/chrome/src/ui/skill-markdown.js
+++ b/src/chrome/src/ui/skill-markdown.js
@@ -4,8 +4,8 @@
*/
import { escapeHtml } from './utils.js';
-import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
+import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';
+import { createMarkdownPlaceholders, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
function renderEmphasis(text) {
return text
@@ -13,84 +13,47 @@ function renderEmphasis(text) {
.replace(/\*(.+?)\*/g, '<em>$1</em>');
}
-function renderInlineMarkdown(value) {
+function renderInlineMarkdown(value, placeholders) {
let text = sanitizeMarkdownLinks(value);
- const links = [];
+ text = linkifyPlainUrls(text);
// Link destinations can legitimately contain `*`. Protect the complete
// sanitized anchor while applying emphasis only to its visible label.
text = text.replace(
- /(<a href="[^"]*" target="_blank" rel="noopener noreferrer">)([\s\S]*?)(<\/a>)/g,
- (_match, open, label, close) => {
- const placeholder = `__SKILL_LINK_${links.length}__`;
- links.push(`${open}${renderEmphasis(label)}${close}`);
- return placeholder;
- },
+ /(<a\b[^>]*>)([\s\S]*?)(<\/a>)/g,
+ (_match, open, label, close) => placeholders.add(`${open}${/^https?:\/\/\S+$/i.test(label) ? label : renderEmphasis(label)}${close}`),
);
- text = renderEmphasis(text);
- links.forEach((link, index) => {
- text = text.replace(`__SKILL_LINK_${index}__`, () => link);
- });
- return text;
+ return renderEmphasis(text);
}
export function renderSkillMarkdown(content) {
let text = String(content || '');
- const codeBlocks = [];
- text = replaceMarkdownCodeFences(text, (_info, code) => {
- const placeholder = `__SKILL_CODE_BLOCK_${codeBlocks.length}__`;
- codeBlocks.push(code);
- return placeholder;
- });
- const inlineCodes = [];
- text = text.replace(/`([^`\n]+)`/g, (_match, code) => {
- const placeholder = `__SKILL_INLINE_CODE_${inlineCodes.length}__`;
- inlineCodes.push(code);
- return placeholder;
- });
+ const placeholders = createMarkdownPlaceholders(text);
+ text = replaceMarkdownCodeFences(text, (_info, code) => placeholders.add(`<pre><code>${escapeHtml(code)}</code></pre>`, code));
+ text = text.replace(/`([^`\n]+)`/g, (_match, code) => placeholders.add(`<code>${escapeHtml(code)}</code>`, code));
text = escapeHtml(text);
text = renderMarkdownTables(text);
- const quoteBlocks = [];
text = text.replace(/(?:^[ \t]*&gt;[^\r\n]*(?:\r?\n|$))+/gm, (block) => {
- const placeholder = `__SKILL_QUOTE_BLOCK_${quoteBlocks.length}__`;
- quoteBlocks.push(block.trimEnd().split(/\r?\n/)
+ const quote = block.trimEnd().split(/\r?\n/)
.map((line) => line.replace(/^[ \t]*&gt;[ \t]?/, ''))
- .join('\n'));
- return `${placeholder}\n`;
+ .join('\n');
+ return `${placeholders.add(`<blockquote>${renderInlineMarkdown(quote, placeholders).replace(/\n/g, '<br>')}</blockquote>`)}\n`;
});
// Pull list markers out before parsing emphasis so a `*` bullet cannot be
// paired with an emphasis marker later in the same item.
- const listBlocks = [];
const extractLists = (input, pattern, tag, markerPattern) => input.replace(pattern, (block) => {
- const placeholder = `__SKILL_LIST_BLOCK_${listBlocks.length}__`;
const items = block.trimEnd().split(/\r?\n/)
.map((line) => line.replace(markerPattern, '').trim());
- listBlocks.push({ tag, items });
- return `${placeholder}\n`;
+ return `${placeholders.add(`<${tag}>${items.map((item) => `<li>${renderInlineMarkdown(item, placeholders)}</li>`).join('')}</${tag}>`)}\n`;
});
text = extractLists(text, /(?:^[ \t]*[-+*][ \t]+[^\r\n]*(?:\r?\n|$))+/gm, 'ul', /^[ \t]*[-+*][ \t]+/);
text = extractLists(text, /(?:^[ \t]*\d+\.[ \t]+[^\r\n]*(?:\r?\n|$))+/gm, 'ol', /^[ \t]*\d+\.[ \t]+/);
- text = renderInlineMarkdown(renderMarkdownHeadings(text)).replace(/\n/g, '<br>');
-
- listBlocks.forEach(({ tag, items }, index) => {
- const block = `<${tag}>${items.map((item) => `<li>${renderInlineMarkdown(item)}</li>`).join('')}</${tag}>`;
- text = text.replace(`__SKILL_LIST_BLOCK_${index}__`, () => block);
- });
- quoteBlocks.forEach((quote, index) => {
- const block = `<blockquote>${renderInlineMarkdown(quote).replace(/\n/g, '<br>')}</blockquote>`;
- text = text.replace(`__SKILL_QUOTE_BLOCK_${index}__`, () => block);
- });
- inlineCodes.forEach((code, index) => {
- text = text.replace(`__SKILL_INLINE_CODE_${index}__`, () => `<code>${escapeHtml(code)}</code>`);
- });
- codeBlocks.forEach((code, index) => {
- text = text.replace(`__SKILL_CODE_BLOCK_${index}__`, () => `<pre><code>${escapeHtml(code)}</code></pre>`);
- });
- return text;
+ text = renderInlineMarkdown(renderMarkdownHeadings(text), placeholders).replace(/\n/g, '<br>');
+ return placeholders.restore(text);
}
diff --git a/src/chrome/styles/sidepanel.css b/src/chrome/styles/sidepanel.css
index 8f94339b1..e25506193 100644
--- a/src/chrome/styles/sidepanel.css
+++ b/src/chrome/styles/sidepanel.css
@@ -2380,6 +2380,47 @@ html[dir="rtl"] .language-picker-menu {
margin-bottom: 0;
}
+.message-content a {
+ color: var(--accent);
+ text-decoration: underline;
+ text-underline-offset: 0.18em;
+ overflow-wrap: anywhere;
+}
+
+.message.user .message-content a {
+ color: inherit;
+}
+
+.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.chat-link-icon-ready::before {
+ display: none;
+}
+
+.message-content .chat-link-icon {
+ display: none;
+ 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;
+}
+
.hint {
color: var(--text-muted);
font-size: 11px;
diff --git a/src/firefox/src/ui/chat-link-icons.js b/src/firefox/src/ui/chat-link-icons.js
new file mode 100644
index 000000000..e22e76cdc
--- /dev/null
+++ b/src/firefox/src/ui/chat-link-icons.js
@@ -0,0 +1,322 @@
+import { linkifyPlainUrls, markdownImageRanges } from './markdown-link.js';
+
+const ICON_SERVICE = 'https://icons.duckduckgo.com/ip3/';
+const MAX_ICON_BYTES = 64 * 1024;
+const RASTER_TYPES = new Set(['image/x-icon', 'image/vnd.microsoft.icon', 'image/ico', 'image/icon', 'image/png', 'image/jpeg', 'image/webp']);
+const CHAT_TEXT_SELECTOR = '.message-text, .slash-command-text';
+const LINKIFY_SKIP_SELECTOR = 'a, pre, code, style, script, button, textarea, [data-no-favicon]';
+const LOCAL_SUFFIXES = ['localhost', 'local', 'localdomain', 'internal', 'intranet', 'lan', 'home', 'corp', 'private', 'test', 'invalid', 'example', 'onion', 'arpa'];
+
+function publicHostname(href, baseURI) {
+ try {
+ const url = new URL(href, baseURI);
+ if (!['http:', 'https:'].includes(url.protocol) || url.username || url.password) return '';
+ const hostname = url.hostname.toLowerCase().replace(/\.$/, '');
+ if (hostname.length > 253 || !hostname.includes('.') || /[:\[\]]/.test(hostname)
+ || /^[\d.]+$/.test(hostname) || LOCAL_SUFFIXES.some(suffix => hostname === suffix || hostname.endsWith(`.${suffix}`))) return '';
+ const labels = hostname.split('.');
+ if (!labels.every(label => /^[a-z\d](?:[a-z\d-]{0,61}[a-z\d])?$/.test(label))
+ || !/^(?:[a-z]{2,63}|xn--[a-z\d-]+)$/.test(labels.at(-1))) return '';
+ return hostname;
+ } catch { return ''; }
+}
+
+function rasterSignature(bytes, mime) {
+ if (mime === 'image/png') return [137, 80, 78, 71, 13, 10, 26, 10].every((value, index) => bytes[index] === value);
+ if (mime === 'image/jpeg') return bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255;
+ if (mime === 'image/webp') return String.fromCharCode(...bytes.slice(0, 4)) === 'RIFF'
+ && String.fromCharCode(...bytes.slice(8, 12)) === 'WEBP';
+ return bytes[0] === 0 && bytes[1] === 0 && bytes[2] === 1 && bytes[3] === 0;
+}
+
+async function readIcon(response) {
+ if (!response.ok) {
+ await response.body?.cancel?.().catch(() => {});
+ throw new Error('Favicon unavailable');
+ }
+ const mime = String(response.headers.get('content-type') || '').split(';')[0].trim().toLowerCase();
+ const size = Number(response.headers.get('content-length'));
+ if (!RASTER_TYPES.has(mime) || size > MAX_ICON_BYTES || !response.body?.getReader) {
+ await response.body?.cancel?.().catch(() => {});
+ throw new Error('Unsupported favicon');
+ }
+ const reader = response.body.getReader();
+ const chunks = [];
+ let total = 0;
+ try {
+ while (true) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ total += value.byteLength;
+ if (total > MAX_ICON_BYTES) throw new Error('Favicon too large');
+ chunks.push(value);
+ }
+ } catch (error) {
+ await reader.cancel().catch(() => {});
+ throw error;
+ } finally { reader.releaseLock(); }
+ const bytes = new Uint8Array(total);
+ let offset = 0;
+ for (const chunk of chunks) { bytes.set(chunk, offset); offset += chunk.byteLength; }
+ if (!rasterSignature(bytes, mime)) throw new Error('Invalid favicon');
+ return new Blob([bytes], { type: mime });
+}
+
+/**
+ * Decorate chat links without allowing model text to choose an image URL.
+ * Only a public hostname reaches the fixed favicon service; paths, queries,
+ * fragments, cookies and referrers are never sent. Failures retain the CSS icon.
+ * The returned function releases observers, requests and local image URLs.
+ */
+export function installChatLinkIcons(root, {
+ fetchImpl = globalThis.fetch,
+ timeoutMs = 5000,
+ maxDomains = 64,
+ concurrency = 4,
+ observerImpl = root?.ownerDocument?.defaultView?.MutationObserver ?? globalThis.MutationObserver,
+ intersectionObserverImpl = root?.ownerDocument?.defaultView?.IntersectionObserver ?? globalThis.IntersectionObserver,
+} = {}) {
+ if (!root?.querySelectorAll) return () => {};
+ const document = root.ownerDocument;
+ const cacheLimit = Math.min(64, Math.max(1, Math.floor(Number(maxDomains) || 64)));
+ const workerLimit = Math.min(4, Math.max(1, Math.floor(Number(concurrency) || 4)));
+ const deadline = Math.min(10000, Math.max(1, Number(timeoutMs) || 5000));
+ const entries = new Map();
+ const decorated = new WeakMap();
+ const inspectedText = new WeakMap();
+ const queue = [];
+ const controllers = new Set();
+ const objectUrls = new Set();
+ const added = new Set();
+ let disposed = false;
+ let scheduled = false;
+ let running = 0;
+
+ function stillCurrent(image, entry) {
+ const link = image.parentElement;
+ return !disposed && root.contains(image) && decorated.get(link)?.image === image
+ && decorated.get(link)?.hostname === entry.hostname;
+ }
+
+ function applyImage(image, entry) {
+ if (!entry.url || !stillCurrent(image, entry)) return;
+ image.onload = () => {
+ if (stillCurrent(image, entry)) image.parentElement.classList.add('chat-link-icon-ready');
+ };
+ image.onerror = () => {
+ if (stillCurrent(image, entry)) image.parentElement.classList.remove('chat-link-icon-ready');
+ image.removeAttribute('src');
+ };
+ image.src = entry.url;
+ }
+
+ async function load(entry) {
+ const controller = new AbortController();
+ controllers.add(controller);
+ let timer;
+ try {
+ const timeout = new Promise((_, reject) => {
+ controller.signal.addEventListener('abort', () => reject(new Error('Favicon request cancelled')), { once: true });
+ timer = setTimeout(() => controller.abort(), deadline);
+ });
+ const result = await Promise.race([
+ Promise.resolve().then(() => {
+ if (controller.signal.aborted) throw new Error('Favicon request cancelled');
+ return fetchImpl(`${ICON_SERVICE}${encodeURIComponent(entry.hostname)}.ico`, {
+ credentials: 'omit', referrerPolicy: 'no-referrer', redirect: 'error', signal: controller.signal,
+ });
+ }).then(readIcon),
+ timeout,
+ ]);
+ if (disposed) return;
+ entry.url = URL.createObjectURL(result);
+ objectUrls.add(entry.url);
+ entry.status = 'ready';
+ for (const image of entry.images) applyImage(image, entry);
+ } catch {
+ entry.status = 'failed';
+ } finally {
+ clearTimeout(timer);
+ controllers.delete(controller);
+ entry.images.clear();
+ running--;
+ pump();
+ }
+ }
+
+ function pump() {
+ while (!disposed && running < workerLimit && queue.length) {
+ const entry = queue.shift();
+ running++;
+ entry.status = 'loading';
+ void load(entry);
+ }
+ }
+
+ function requestIcon(link) {
+ const state = decorated.get(link);
+ if (disposed || !state?.image || !root.contains(link)) return;
+ let entry = entries.get(state.hostname);
+ if (!entry) {
+ // A hard per-panel bound prevents long chats or streamed replacements
+ // from causing unbounded lookups or an eviction/re-fetch loop.
+ if (entries.size >= cacheLimit || typeof fetchImpl !== 'function') return;
+ entry = { hostname: state.hostname, status: 'queued', url: '', images: new Set() };
+ entries.set(state.hostname, entry);
+ queue.push(entry);
+ }
+ if (entry.status === 'ready') applyImage(state.image, entry);
+ else if (entry.status !== 'failed') {
+ for (const image of entry.images) if (!stillCurrent(image, entry)) entry.images.delete(image);
+ entry.images.add(state.image);
+ }
+ pump();
+ }
+
+ const visibility = typeof intersectionObserverImpl === 'function' ? new intersectionObserverImpl(records => {
+ for (const record of records) if (record.isIntersecting) {
+ visibility.unobserve(record.target);
+ requestIcon(record.target);
+ }
+ }) : null;
+
+ function precedingChatText(node) {
+ const parent = node.nodeType === 1 ? node : node.parentElement;
+ const message = parent?.closest(CHAT_TEXT_SELECTOR);
+ if (!message || message === node) return '';
+ const walker = document.createTreeWalker(message, 5, {
+ acceptNode: child => child.nodeType === 1
+ ? (child.matches('pre, code, style, script, button, textarea') ? 2 : 1) : 1,
+ });
+ let text = '';
+ while (walker.nextNode() && walker.currentNode !== node) {
+ if (walker.currentNode.nodeType === 3) text += walker.currentNode.textContent;
+ }
+ return text;
+ }
+
+ function decorate(link) {
+ if (!root.contains(link)) return;
+ const href = link.getAttribute('href');
+ // Older saved HTML can contain !<a>, or an auto-link inside unfinished image
+ // syntax. Include earlier inline siblings so formatting cannot hide it.
+ if (!link.hasAttribute('data-no-favicon')) {
+ const prefix = precedingChatText(link);
+ if (prefix.endsWith('!') || markdownImageRanges(prefix + link.textContent)
+ .some(([start, end]) => start < prefix.length && end > prefix.length)) {
+ link.setAttribute('data-no-favicon', 'true');
+ }
+ }
+ if (href !== null) {
+ link.target = '_blank';
+ const rel = new Set(String(link.getAttribute('rel') || '').split(/\s+/).filter(Boolean));
+ rel.add('noopener'); rel.add('noreferrer');
+ link.setAttribute('rel', [...rel].join(' '));
+ }
+ const hostname = href !== null && !link.hasAttribute('download') && !link.closest('pre, code, [data-no-favicon]')
+ ? publicHostname(href, document.baseURI) : '';
+ const previous = decorated.get(link);
+ if (previous?.hostname === hostname && previous?.href === href) return;
+ visibility?.unobserve(link);
+ if (previous?.image) entries.get(previous.hostname)?.images.delete(previous.image);
+ previous?.image?.remove();
+ // Restored chat HTML may contain an object URL from a closed panel.
+ for (const image of link.querySelectorAll('.chat-link-icon')) image.remove();
+ link.classList.remove('chat-link-icon-ready');
+ link.classList.toggle('chat-link', Boolean(hostname));
+ const state = { href, hostname, image: null };
+ decorated.set(link, state);
+ if (!hostname) return;
+ const image = document.createElement('img');
+ image.className = 'chat-link-icon';
+ image.alt = '';
+ image.setAttribute('aria-hidden', 'true');
+ image.width = 14; image.height = 14;
+ image.decoding = 'async';
+ image.referrerPolicy = 'no-referrer';
+ state.image = image;
+ link.prepend(image);
+ if (visibility) visibility.observe(link);
+ else requestIcon(link);
+ }
+
+ function linkifyTextNode(node) {
+ const parent = node.parentElement;
+ if (!parent?.closest(CHAT_TEXT_SELECTOR) || parent.closest(LINKIFY_SKIP_SELECTOR)) return;
+ const text = node.textContent;
+ if (inspectedText.get(node) === text) return;
+ inspectedText.set(node, text);
+ if (!/https?:\/\//i.test(text)) return;
+ const escaped = text.replace(/[&<>"']/g, character => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ })[character]);
+ const html = linkifyPlainUrls(escaped, precedingChatText(node));
+ if (!html.includes('<a ')) return;
+ const template = document.createElement('template');
+ template.innerHTML = html;
+ const links = [...template.content.querySelectorAll('a')];
+ node.replaceWith(template.content);
+ for (const link of links) decorate(link);
+ }
+
+ function scan(node) {
+ if (node.nodeType === 3) { linkifyTextNode(node); return; }
+ if (node.nodeType !== 1) return;
+ if (node.matches('a')) decorate(node);
+ for (const link of node.querySelectorAll('a[href]')) decorate(link);
+ // Saved chat HTML predates the formatter change. Upgrade only the newly
+ // restored subtree, never code or existing links, without rerendering it.
+ const walker = document.createTreeWalker(node, 5, {
+ acceptNode: child => child.nodeType === 1 ? (child.matches(LINKIFY_SKIP_SELECTOR) ? 2 : 3) : 1,
+ });
+ const textNodes = [];
+ while (walker.nextNode()) textNodes.push(walker.currentNode);
+ for (const text of textNodes) linkifyTextNode(text);
+ }
+
+ function detach(node) {
+ if (node.nodeType !== 1 || root.contains(node)) return;
+ const links = [...(node.matches('a') ? [node] : []), ...node.querySelectorAll('a')];
+ for (const link of links) {
+ visibility?.unobserve(link);
+ const state = decorated.get(link);
+ if (state?.image) entries.get(state.hostname)?.images.delete(state.image);
+ decorated.delete(link);
+ }
+ }
+
+ const observer = typeof observerImpl === 'function' ? new observerImpl(records => {
+ for (const record of records) {
+ if (record.type === 'attributes' || record.type === 'characterData') added.add(record.target);
+ else {
+ for (const node of record.removedNodes) detach(node);
+ for (const node of record.addedNodes) if (node.nodeType === 1 || node.nodeType === 3) added.add(node);
+ }
+ }
+ if (scheduled || !added.size) return;
+ scheduled = true;
+ queueMicrotask(() => {
+ scheduled = false;
+ if (disposed) return;
+ const nodes = new Set(added); added.clear();
+ for (const node of nodes) {
+ if (!root.contains(node)) continue;
+ let parent = node.parentNode;
+ while (parent && !nodes.has(parent)) parent = parent.parentNode;
+ if (!parent) scan(node);
+ }
+ });
+ }) : null;
+ scan(root);
+ observer?.observe(root, { subtree: true, childList: true, characterData: true, attributes: true, attributeFilter: ['href', 'data-no-favicon', 'download'] });
+
+ return () => {
+ disposed = true;
+ observer?.disconnect(); visibility?.disconnect();
+ added.clear(); queue.length = 0;
+ for (const controller of controllers) controller.abort();
+ controllers.clear();
+ for (const url of objectUrls) URL.revokeObjectURL(url);
+ objectUrls.clear(); entries.clear();
+ };
+}
diff --git a/src/firefox/src/ui/markdown-link.js b/src/firefox/src/ui/markdown-link.js
index faa9716e8..b8481f26c 100644
--- a/src/firefox/src/ui/markdown-link.js
+++ b/src/firefox/src/ui/markdown-link.js
@@ -55,5 +55,105 @@ export function sanitizeLink(label, href) {
* sanitizeLink. Non-link text is passed through unchanged.
*/
export function sanitizeMarkdownLinks(text) {
- return String(text == null ? '' : text).replace(MD_LINK_RE, (_m, label, href) => sanitizeLink(label, href));
+ return String(text == null ? '' : text).replace(MD_LINK_RE, (_m, label, href, offset, source) => {
+ const link = sanitizeLink(label, href);
+ // Markdown images stay links, without even an indirect favicon request.
+ if (source[offset - 1] !== '!') return link;
+ return link.startsWith('<a ') ? link.replace(/^<a /, '<a data-no-favicon="true" ')
+ : `<span data-no-favicon="true">${label}</span>`;
+ });
+}
+
+// Image syntax is inert even before streaming has supplied its closing bracket
+// or parenthesis. Track balanced delimiters instead of assuming a URL following
+// an unfinished image is ordinary prose. Ranges include labels as well as URLs.
+export function markdownImageRanges(text) {
+ const source = String(text ?? '');
+ const ranges = [];
+ let cursor = 0;
+ const balancedEnd = (start, open, close) => {
+ let depth = 1;
+ for (let index = start + 1; index < source.length; index++) {
+ if (source[index] === '\\') { index++; continue; }
+ if (source[index] === open) depth++;
+ else if (source[index] === close && --depth === 0) return index + 1;
+ }
+ return source.length;
+ };
+ while ((cursor = source.indexOf('![', cursor)) !== -1) {
+ const start = cursor;
+ let end = balancedEnd(cursor + 1, '[', ']');
+ if (source[end] === '(') end = balancedEnd(end, '(', ')');
+ else if (source[end] === '[') end = balancedEnd(end, '[', ']');
+ ranges.push([start, end]);
+ cursor = Math.max(end, start + 2);
+ }
+ return ranges;
+}
+
+// Input is already HTML-escaped, with fixed Markdown markup added. Only text
+// nodes are linkified: existing anchors, code and generated attributes stay intact.
+export function linkifyPlainUrls(html, precedingText = '') {
+ const source = String(html ?? '');
+ const protectedTags = new Set(['a', 'code', 'pre']);
+ let protectedDepth = 0;
+ // Ignore generated tags while retaining offsets and syntax across inline
+ // formatting. Literal code or existing links cannot start image syntax in
+ // adjacent prose. Restored DOM text supplies earlier siblings as context.
+ const imageContext = source.replace(/<[^>]*>|[^<]+|</g, token => {
+ if (token.startsWith('<')) {
+ const tag = /^<(\/?)([a-z][\w-]*)\b/i.exec(token);
+ if (tag && protectedTags.has(tag[2].toLowerCase())) {
+ protectedDepth = Math.max(0, protectedDepth + (tag[1] ? -1 : 1));
+ }
+ return ' '.repeat(token.length);
+ }
+ return protectedDepth ? ' '.repeat(token.length) : token;
+ });
+ const imageRanges = markdownImageRanges(precedingText + imageContext);
+ protectedDepth = 0;
+ return source.replace(/<[^>]*>|[^<]+|</g, (token, tokenOffset) => {
+ if (token.startsWith('<')) {
+ const tag = /^<(\/?)([a-z][\w-]*)\b/i.exec(token);
+ if (tag && protectedTags.has(tag[2].toLowerCase())) {
+ protectedDepth = Math.max(0, protectedDepth + (tag[1] ? -1 : 1));
+ }
+ return token;
+ }
+ if (protectedDepth) return token;
+ return token.replace(/\bhttps?:\/\/(?:(?!&(?:lt|gt|quot|apos|#39|#34);)[^\s<>"'`])+/gi, (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.
+ if (offset && /[\w@:/]/.test(source[offset - 1])) return candidate;
+ let end = candidate.length;
+ const emphasis = /(?:^|[\s(\[{>])(\*{1,3})(?=\S|$)[^*\n]*$/.exec(source.slice(0, offset))?.[1];
+ let closedEmphasis = false;
+ const pairs = { ')': '(', ']': '[', '}': '{' };
+ const balance = { '(': 0, '[': 0, '{': 0 };
+ for (const character of candidate) {
+ if (Object.hasOwn(balance, character)) balance[character]++;
+ else if (pairs[character]) balance[pairs[character]]--;
+ }
+ while (end) {
+ const last = candidate[end - 1];
+ if (!closedEmphasis && emphasis && candidate.slice(0, end).endsWith(emphasis)) {
+ end -= emphasis.length;
+ closedEmphasis = true;
+ continue;
+ }
+ if (last === ';' && /&(?:amp|#\d+|#x[\da-f]+);$/i.test(candidate.slice(0, end))) break;
+ if (/[.,!?;:]/.test(last)) { end--; continue; }
+ const opening = pairs[last];
+ if (opening && balance[opening] < 0) { balance[opening]++; end--; continue; }
+ break;
+ }
+ const href = candidate.slice(0, end);
+ try {
+ const parsed = new URL(href.replace(/&amp;/g, '&'));
+ if (!parsed.hostname || !['http:', 'https:'].includes(parsed.protocol)) return candidate;
+ } catch { return candidate; }
+ return sanitizeLink(href, href) + candidate.slice(end);
+ });
+ });
}
diff --git a/src/firefox/src/ui/markdown-render.js b/src/firefox/src/ui/markdown-render.js
index 954ac8c99..53e6410b9 100644
--- a/src/firefox/src/ui/markdown-render.js
+++ b/src/firefox/src/ui/markdown-render.js
@@ -50,6 +50,37 @@ export function escapeCodeHtml(value) {
}[character]));
}
+// Pick a namespace absent from the source, and restore only the tokens that
+// existed before this pass. Model text must never name or recursively expand
+// one of the renderer's HTML fragments.
+export function createMarkdownPlaceholders(source) {
+ const occupied = new Set([...String(source).matchAll(/WBMD(\d+)TOKEN/g)].map(match => match[1]));
+ let namespace = 0;
+ while (occupied.has(String(namespace))) namespace++;
+ const prefix = `WBMD${namespace}TOKEN`;
+ const tokenPattern = new RegExp(`${prefix}(\\d+)END`, 'g');
+ const htmlPattern = new RegExp(`<[^>]*>|${prefix}(\\d+)END`, 'g');
+ const fragments = [];
+ const restore = value => String(value).replace(htmlPattern, (match, index) => {
+ if (index !== undefined) return fragments[Number(index)]?.html ?? match;
+ // Inline code can occur inside a Markdown destination. It is attribute
+ // text there, never HTML, even when the same fragment is markup in a label.
+ return match.replace(tokenPattern, (token, id) => {
+ const fragment = fragments[Number(id)];
+ return fragment ? escapeCodeHtml(fragment.text) : token;
+ });
+ });
+ return {
+ restore,
+ add(html, text = '') {
+ const rendered = restore(html);
+ const token = `${prefix}${fragments.length}END`;
+ fragments.push({ html: rendered, text });
+ return token;
+ },
+ };
+}
+
export function normalizeCodeLanguage(language) {
return LANGUAGE_ALIASES[String(language || '').trim().toLowerCase()] || '';
}
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index e574a73a1..4ebb03631 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -14,8 +14,9 @@ import { mountActivityBrain } from './activity-brain.js';
import { createComposerModePins } from './composer-mode-pin.js';
import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';
import { CAPABILITY_LABEL } from '../agent/permission-gate.js';
-import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
+import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';
+import { installChatLinkIcons } from './chat-link-icons.js';
+import { codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
import { applyMode, loadMode, watch } from './theme.js';
import {
UI_SCALE_LEVELS,
@@ -569,6 +570,14 @@ if (globalThis.browser?.storage?.onChanged) {
})();
const messagesEl = document.getElementById('messages');
+const disposeChatLinkIcons = installChatLinkIcons(messagesEl, {
+ fetchImpl: async (url, options) => {
+ const { strictSecretMode } = await chrome.storage.local.get('strictSecretMode');
+ if (strictSecretMode === true) throw new Error('Remote chat icons are disabled in Strict Secret Mode.');
+ return fetch(url, options);
+ },
+});
+window.addEventListener('pagehide', disposeChatLinkIcons, { once: true });
const chatContainerEl = document.getElementById('chat-container');
const chatNavigationEl = document.getElementById('chat-navigation');
const chatNavigationActionEl = document.getElementById('chat-navigation-action');
@@ -5062,6 +5071,8 @@ async function exportSavedWorkflow(id, tabId = currentTabId) {
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
+ link.target = '_blank';
+ link.rel = 'noopener noreferrer';
link.download = savedWorkflowDownloadFilename(res.workflow.name);
document.body.appendChild(link);
try {
@@ -9623,6 +9634,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-config-${Date.now()}.json`;
document.body.appendChild(a);
try {
@@ -9669,6 +9682,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-traces-${Date.now()}.${res.json ? 'json' : 'md'}`;
document.body.appendChild(a);
try {
@@ -9713,6 +9728,8 @@ async function parseSlashCommands(text, tabId = currentTabId, options = {}) {
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
+ a.target = '_blank';
+ a.rel = 'noopener noreferrer';
a.download = `webbrain-chat-${Date.now()}.md`;
document.body.appendChild(a);
try {
@@ -14424,21 +14441,27 @@ function formatMarkdown(text, options = {}) {
const enhance = options.enhance !== false;
const streaming = options.recoverNestedMarkdown === true;
+ const placeholders = createMarkdownPlaceholders(text);
+
// 1. Extract fenced code blocks BEFORE escaping HTML
const codeBlocks = [];
text = replaceMarkdownCodeFences(text, (info, code) => {
const lang = codeFenceLanguage(info);
- const id = `__CODEBLOCK_${codeBlocks.length}__`;
+ const index = codeBlocks.length;
codeBlocks.push({ lang: lang || '', code });
- return id;
+ const highlighted = enhance ? highlightCode(code, lang) : escapeHtml(code);
+ const langLabel = lang ? `<span class="code-lang">${escapeHtml(lang)}</span>` : '';
+ const copyBtn = enhance
+ ? `<button class="code-copy-btn" data-code-index="${index}" title="${escapeHtml(t('sp.copy.code.title'))}">${escapeHtml(t('sp.copy'))}</button>`
+ : '';
+ const header = langLabel || copyBtn ? `<div class="code-block-header">${langLabel}${copyBtn}</div>` : '';
+ return placeholders.add(`<div class="code-block-wrapper">${header}<pre><code>${highlighted}</code></pre></div>`, code);
}, { streaming });
// 2. Extract inline code before escaping
- const inlineCodes = [];
text = text.replace(/`([^`\n]+)`/g, (_match, code) => {
- const id = `__INLINE_${inlineCodes.length}__`;
- inlineCodes.push(code);
- return id;
+ const escaped = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
+ return placeholders.add(`<code>${escaped}</code>`, code);
});
// 3. Escape HTML in the remaining text
@@ -14455,38 +14478,15 @@ function formatMarkdown(text, options = {}) {
text = renderMarkdownTables(text);
text = renderMarkdownBlockquotes(text);
text = renderMarkdownHeadings(text);
- text = text
+ const emphasis = value => value
.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
.replace(/\*(.+?)\*/g, '<em>$1</em>');
- text = sanitizeMarkdownLinks(text);
- text = text.replace(/\n/g, '<br>');
-
- // 5. Restore inline code
- inlineCodes.forEach((code, i) => {
- const escaped = code.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
- // Function replacer: a string replacement would interpret `$&`, `$\``, etc.
- // in code that contains literal `$` sequences (shell, jQuery, regex), mangling it.
- text = text.replace(`__INLINE_${i}__`, () => `<code>${escaped}</code>`);
- });
-
- // 6. Restore fenced code blocks with copy button
- codeBlocks.forEach((block, i) => {
- // Re-highlighting every accumulated token is expensive and can visibly
- // flicker. Keep live code escaped/plain, then highlight it once when the
- // authoritative terminal response arrives.
- const highlighted = enhance ? highlightCode(block.code, block.lang) : escapeHtml(block.code);
- const langLabel = block.lang ? `<span class="code-lang">${escapeHtml(block.lang)}</span>` : '';
- const copyBtn = enhance
- ? `<button class="code-copy-btn" data-code-index="${i}" title="${escapeHtml(t('sp.copy.code.title'))}">${escapeHtml(t('sp.copy'))}</button>`
- : '';
- const header = langLabel || copyBtn
- ? `<div class="code-block-header">${langLabel}${copyBtn}</div>`
- : '';
- text = text.replace(
- `__CODEBLOCK_${i}__`,
- () => `<div class="code-block-wrapper">${header}<pre><code>${highlighted}</code></pre></div>`
- );
- });
+ // Protect destinations from emphasis (a URL can itself contain '*').
+ text = linkifyPlainUrls(sanitizeMarkdownLinks(text)).replace(/(<a\b[^>]*>)([\s\S]*?)(<\/a>)/g, (_match, open, label, close) => (
+ placeholders.add(`${open}${/^https?:\/\/\S+$/i.test(label) ? label : emphasis(label)}${close}`)
+ ));
+ text = emphasis(text).replace(/\n/g, '<br>');
+ text = placeholders.restore(text);
// Schedule KaTeX rendering of any math expressions in the messages area.
if (enhance) scheduleMathRender();
diff --git a/src/firefox/src/ui/skill-markdown.js b/src/firefox/src/ui/skill-markdown.js
index 2dd0f4ac6..004b59d09 100644
--- a/src/firefox/src/ui/skill-markdown.js
+++ b/src/firefox/src/ui/skill-markdown.js
@@ -4,8 +4,8 @@
*/
import { escapeHtml } from './utils.js';
-import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
+import { sanitizeMarkdownLinks, linkifyPlainUrls } from './markdown-link.js';
+import { createMarkdownPlaceholders, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
function renderEmphasis(text) {
return text
@@ -13,84 +13,47 @@ function renderEmphasis(text) {
.replace(/\*(.+?)\*/g, '<em>$1</em>');
}
-function renderInlineMarkdown(value) {
+function renderInlineMarkdown(value, placeholders) {
let text = sanitizeMarkdownLinks(value);
- const links = [];
+ text = linkifyPlainUrls(text);
// Link destinations can legitimately contain `*`. Protect the complete
// sanitized anchor while applying emphasis only to its visible label.
text = text.replace(
- /(<a href="[^"]*" target="_blank" rel="noopener noreferrer">)([\s\S]*?)(<\/a>)/g,
- (_match, open, label, close) => {
- const placeholder = `__SKILL_LINK_${links.length}__`;
- links.push(`${open}${renderEmphasis(label)}${close}`);
- return placeholder;
- },
+ /(<a\b[^>]*>)([\s\S]*?)(<\/a>)/g,
+ (_match, open, label, close) => placeholders.add(`${open}${/^https?:\/\/\S+$/i.test(label) ? label : renderEmphasis(label)}${close}`),
);
- text = renderEmphasis(text);
- links.forEach((link, index) => {
- text = text.replace(`__SKILL_LINK_${index}__`, () => link);
- });
- return text;
+ return renderEmphasis(text);
}
export function renderSkillMarkdown(content) {
let text = String(content || '');
- const codeBlocks = [];
- text = replaceMarkdownCodeFences(text, (_info, code) => {
- const placeholder = `__SKILL_CODE_BLOCK_${codeBlocks.length}__`;
- codeBlocks.push(code);
- return placeholder;
- });
- const inlineCodes = [];
- text = text.replace(/`([^`\n]+)`/g, (_match, code) => {
- const placeholder = `__SKILL_INLINE_CODE_${inlineCodes.length}__`;
- inlineCodes.push(code);
- return placeholder;
- });
+ const placeholders = createMarkdownPlaceholders(text);
+ text = replaceMarkdownCodeFences(text, (_info, code) => placeholders.add(`<pre><code>${escapeHtml(code)}</code></pre>`, code));
+ text = text.replace(/`([^`\n]+)`/g, (_match, code) => placeholders.add(`<code>${escapeHtml(code)}</code>`, code));
text = escapeHtml(text);
text = renderMarkdownTables(text);
- const quoteBlocks = [];
text = text.replace(/(?:^[ \t]*&gt;[^\r\n]*(?:\r?\n|$))+/gm, (block) => {
- const placeholder = `__SKILL_QUOTE_BLOCK_${quoteBlocks.length}__`;
- quoteBlocks.push(block.trimEnd().split(/\r?\n/)
+ const quote = block.trimEnd().split(/\r?\n/)
.map((line) => line.replace(/^[ \t]*&gt;[ \t]?/, ''))
- .join('\n'));
- return `${placeholder}\n`;
+ .join('\n');
+ return `${placeholders.add(`<blockquote>${renderInlineMarkdown(quote, placeholders).replace(/\n/g, '<br>')}</blockquote>`)}\n`;
});
// Pull list markers out before parsing emphasis so a `*` bullet cannot be
// paired with an emphasis marker later in the same item.
- const listBlocks = [];
const extractLists = (input, pattern, tag, markerPattern) => input.replace(pattern, (block) => {
- const placeholder = `__SKILL_LIST_BLOCK_${listBlocks.length}__`;
const items = block.trimEnd().split(/\r?\n/)
.map((line) => line.replace(markerPattern, '').trim());
- listBlocks.push({ tag, items });
- return `${placeholder}\n`;
+ return `${placeholders.add(`<${tag}>${items.map((item) => `<li>${renderInlineMarkdown(item, placeholders)}</li>`).join('')}</${tag}>`)}\n`;
});
text = extractLists(text, /(?:^[ \t]*[-+*][ \t]+[^\r\n]*(?:\r?\n|$))+/gm, 'ul', /^[ \t]*[-+*][ \t]+/);
text = extractLists(text, /(?:^[ \t]*\d+\.[ \t]+[^\r\n]*(?:\r?\n|$))+/gm, 'ol', /^[ \t]*\d+\.[ \t]+/);
- text = renderInlineMarkdown(renderMarkdownHeadings(text)).replace(/\n/g, '<br>');
-
- listBlocks.forEach(({ tag, items }, index) => {
- const block = `<${tag}>${items.map((item) => `<li>${renderInlineMarkdown(item)}</li>`).join('')}</${tag}>`;
- text = text.replace(`__SKILL_LIST_BLOCK_${index}__`, () => block);
- });
- quoteBlocks.forEach((quote, index) => {
- const block = `<blockquote>${renderInlineMarkdown(quote).replace(/\n/g, '<br>')}</blockquote>`;
- text = text.replace(`__SKILL_QUOTE_BLOCK_${index}__`, () => block);
- });
- inlineCodes.forEach((code, index) => {
- text = text.replace(`__SKILL_INLINE_CODE_${index}__`, () => `<code>${escapeHtml(code)}</code>`);
- });
- codeBlocks.forEach((code, index) => {
- text = text.replace(`__SKILL_CODE_BLOCK_${index}__`, () => `<pre><code>${escapeHtml(code)}</code></pre>`);
- });
- return text;
+ text = renderInlineMarkdown(renderMarkdownHeadings(text), placeholders).replace(/\n/g, '<br>');
+ return placeholders.restore(text);
}
diff --git a/src/firefox/styles/sidepanel.css b/src/firefox/styles/sidepanel.css
index 371326615..fb8c44435 100644
--- a/src/firefox/styles/sidepanel.css
+++ b/src/firefox/styles/sidepanel.css
@@ -2212,6 +2212,47 @@ html[dir="rtl"] .language-picker-menu {
margin-bottom: 0;
}
+.message-content a {
+ color: var(--accent);
+ text-decoration: underline;
+ text-underline-offset: 0.18em;
+ overflow-wrap: anywhere;
+}
+
+.message.user .message-content a {
+ color: inherit;
+}
+
+.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.chat-link-icon-ready::before {
+ display: none;
+}
+
+.message-content .chat-link-icon {
+ display: none;
+ 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;
+}
+
.hint {
color: var(--text-muted);
font-size: 11px;
diff --git a/test/chat-links.mjs b/test/chat-links.mjs
new file mode 100644
index 000000000..8f5264ec0
--- /dev/null
+++ b/test/chat-links.mjs
@@ -0,0 +1,569 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import { test } from 'node:test';
+
+const readUi = (build, file) => fs.readFileSync(new URL(`../src/${build}/src/ui/${file}`, import.meta.url), 'utf8');
+const formatterSource = build => {
+ const source = readUi(build, 'sidepanel.js');
+ const start = source.indexOf('function formatMarkdown(');
+ assert.ok(start >= 0);
+ return source.slice(start, source.indexOf('\n}', start) + 2);
+};
+const anchorTags = html => [...html.matchAll(/<a\b[^>]*>/g)].map(match => match[0]);
+const hrefs = html => anchorTags(html).map(tag => tag.match(/\bhref="([^"]*)"/)?.[1]);
+
+for (const build of ['chrome', 'firefox']) {
+ const links = await import(`../src/${build}/src/ui/markdown-link.js`);
+ const helpers = await import(`../src/${build}/src/ui/markdown-render.js`);
+ const { escapeHtml } = await import(`../src/${build}/src/ui/utils.js`);
+ const { renderSkillMarkdown } = await import(`../src/${build}/src/ui/skill-markdown.js`);
+ const formatMarkdown = vm.runInNewContext(`(${formatterSource(build)})`, {
+ ...helpers, ...links, escapeHtml, t: key => key,
+ scheduleMathRender() {}, setTimeout() {},
+ });
+
+ test(`${build}: plain Google Finance URLs become complete links that open new tabs`, () => {
+ const source = "Here's the Google Finance page:\n\nhttps://www.google.com/finance/quote/BZ:NASDAQ\n\nThe Hong Kong listing is https://www.google.com/finance/quote/2076:HKG.";
+ const html = formatMarkdown(source);
+ assert.deepEqual(hrefs(html), [
+ 'https://www.google.com/finance/quote/BZ:NASDAQ',
+ 'https://www.google.com/finance/quote/2076:HKG',
+ ]);
+ for (const anchor of anchorTags(html)) {
+ assert.match(anchor, /\btarget="_blank"/);
+ assert.match(anchor, /\brel="noopener noreferrer"/);
+ }
+ assert.match(html, /2076:HKG<\/a>\./);
+ });
+
+ test(`${build}: URL query parameters survive HTML escaping exactly once`, () => {
+ const html = formatMarkdown('https://example.com/search?q=fish&lang=en#result');
+ assert.deepEqual(hrefs(html), ['https://example.com/search?q=fish&amp;lang=en#result']);
+ assert.doesNotMatch(html, /&amp;amp;/);
+ assert.match(html, />https:\/\/example.com\/search\?q=fish&amp;lang=en#result<\/a>/);
+ });
+
+ test(`${build}: sentence punctuation and surrounding parentheses stay outside links`, () => {
+ const html = formatMarkdown('Read (https://en.wikipedia.org/wiki/JavaScript_(programming_language)), then https://example.com/help!');
+ assert.deepEqual(hrefs(html), [
+ 'https://en.wikipedia.org/wiki/JavaScript_(programming_language)',
+ 'https://example.com/help',
+ ]);
+ assert.match(html, /programming_language\)<\/a>\),/);
+ assert.match(html, /help<\/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']);
+ assert.match(html, /&lt;<a\b/);
+ assert.match(html, /<\/a>&gt;\./);
+ });
+
+ test(`${build}: explicit Markdown links and URL labels never become nested anchors`, () => {
+ const html = formatMarkdown('[https://example.com/label](https://example.com/destination) and https://other.example/path');
+ assert.deepEqual(hrefs(html), ['https://example.com/destination', 'https://other.example/path']);
+ assert.match(html, />https:\/\/example.com\/label<\/a>/);
+ assert.doesNotMatch(html, /<a\b[^>]*>[^<]*<a\b/);
+ });
+
+ test(`${build}: inline and fenced code remain literal while adjacent prose is linked`, () => {
+ const source = '`https://inline.example/path`\n\n```text\nhttps://code.example/path\n[x](https://code.example/markdown)\n```\n\nhttps://visible.example/path';
+ const html = formatMarkdown(source, { enhance: false });
+ assert.deepEqual(hrefs(html), ['https://visible.example/path']);
+ assert.match(html, /<code>https:\/\/inline.example\/path<\/code>/);
+ assert.match(html, /<pre><code>https:\/\/code.example\/path\n\[x\]\(https:\/\/code.example\/markdown\)\n<\/code><\/pre>/);
+ });
+
+ test(`${build}: streamed and final text both linkify without duplicate markup`, () => {
+ const source = 'Reference: https://example.com/article';
+ for (const enhance of [false, true]) {
+ const html = formatMarkdown(source, { enhance, recoverNestedMarkdown: true });
+ assert.deepEqual(hrefs(html), ['https://example.com/article']);
+ assert.equal(links.linkifyPlainUrls(html), html);
+ }
+ });
+
+ test(`${build}: linkification skips existing HTML attributes, anchors and code elements`, () => {
+ const source = '<span title="https://attribute.example/path">https://visible.example/path</span><a href="https://existing.example/path" target="_blank" rel="noopener noreferrer">https://label.example/path</a><code>https://code.example/path</code><pre>https://pre.example/path</pre>';
+ const html = links.linkifyPlainUrls(source);
+ assert.deepEqual(hrefs(html), ['https://visible.example/path', 'https://existing.example/path']);
+ assert.match(html, /title="https:\/\/attribute.example\/path"/);
+ assert.match(html, /<code>https:\/\/code.example\/path<\/code>/);
+ assert.match(html, /<pre>https:\/\/pre.example\/path<\/pre>/);
+ });
+
+ test(`${build}: unsafe URL schemes never become clickable`, () => {
+ const html = formatMarkdown('javascript:alert(1) data:text/html,hello file:///etc/passwd [bad](javascript:alert(1)) [data](data:text/html,bad)');
+ assert.deepEqual(hrefs(html), []);
+ assert.doesNotMatch(html, /<script|<img|\son\w+=/i);
+ });
+
+ test(`${build}: model-authored HTML stays text and quotes cannot add attributes`, () => {
+ const html = formatMarkdown('<img src=x onerror=alert(1)> https://example.com/path" onmouseover="alert(1)');
+ assert.doesNotMatch(html, /<img\b|<script\b/);
+ assert.match(html, /&lt;img src=x onerror=alert\(1\)&gt;/);
+ assert.equal(anchorTags(html).length, 1);
+ assert.doesNotMatch(anchorTags(html)[0], /\son\w+=/i);
+ assert.deepEqual(hrefs(html), ['https://example.com/path']);
+ });
+
+ test(`${build}: Markdown images remain inert and opt out of favicon loading`, () => {
+ const html = formatMarkdown('![tracking](https://tracking.example/pixel?secret=value)');
+ assert.doesNotMatch(html, /<img\b/);
+ assert.equal(anchorTags(html).length, 1);
+ assert.match(anchorTags(html)[0], /\bdata-no-favicon(?:=|\s|>)/);
+ });
+
+ test(`${build}: link restoration cannot interpret placeholder text inside a destination`, () => {
+ for (const [render, token] of [[formatMarkdown, '__CHAT_LINK_1__'], [renderSkillMarkdown, '__SKILL_LINK_1__']]) {
+ const firstHref = `https://trusted.com/${token}`;
+ const secondHref = 'https://x style=background-image:url(https://tracker.com/secret) x=y';
+ const html = render(`[a](${firstHref}) [b](${secondHref})`, { enhance: false });
+ assert.deepEqual(hrefs(html), [firstHref, secondHref]);
+ assert.doesNotMatch(html, /<a\b[^>]*<a\b/);
+ }
+ });
+
+ test(`${build}: literal formatter tokens cannot steal generated links or code`, () => {
+ const cases = [
+ [formatMarkdown, '__CHAT_LINK_0__', '[link](https://trusted.com/docs)', /<a\b[^>]*>link<\/a>/],
+ [formatMarkdown, '__INLINE_0__', '`literal code`', /<code>literal code<\/code>/],
+ [formatMarkdown, '__CODEBLOCK_0__', '```text\nfenced code\n```', /<pre><code>fenced code\n<\/code><\/pre>/],
+ [renderSkillMarkdown, '__SKILL_LINK_0__', '[link](https://trusted.com/docs)', /<a\b[^>]*>link<\/a>/],
+ [renderSkillMarkdown, '__SKILL_INLINE_CODE_0__', '`literal code`', /<code>literal code<\/code>/],
+ [renderSkillMarkdown, '__SKILL_CODE_BLOCK_0__', '```text\nfenced code\n```', /<pre><code>fenced code\n<\/code><\/pre>/],
+ ];
+ for (const [render, token, markdown, expected] of cases) {
+ const html = render(`${token}\n\n${markdown}`, { enhance: false });
+ assert.ok(html.startsWith(token), `source token ${token} must stay literal`);
+ assert.match(html.slice(token.length), expected);
+ }
+ });
+
+ test(`${build}: code placeholders inside links and other code remain source text`, () => {
+ for (const [render, inline, fenced] of [
+ [formatMarkdown, '__INLINE_0__', '__CODEBLOCK_0__'],
+ [renderSkillMarkdown, '__SKILL_INLINE_CODE_0__', '__SKILL_CODE_BLOCK_0__'],
+ ]) {
+ const source = `[inline](https://trusted.com/${inline}) [fenced](https://trusted.com/${fenced})\n\n\`${fenced}\`\n\n\`\`\`text\n${inline}\n\`\`\``;
+ const html = render(source, { enhance: false });
+ assert.deepEqual(hrefs(html), [`https://trusted.com/${inline}`, `https://trusted.com/${fenced}`]);
+ assert.ok(html.includes(`<code>${fenced}</code>`));
+ assert.ok(html.includes(`<pre><code>${inline}\n</code></pre>`));
+ }
+ });
+
+ test(`${build}: current placeholder namespaces in model text remain literal`, () => {
+ const tokens = ['WBMD0TOKEN0END', 'WBMD1TOKEN1END', 'WBMD2TOKEN2END'];
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ const source = `${tokens.join(' ')}\n\n[a](https://trusted.com/${tokens[0]}) [b](https://trusted.com/${tokens[1]})\n\n\`${tokens[2]}\``;
+ const html = render(source, { enhance: false });
+ assert.ok(html.startsWith(tokens.join(' ')));
+ assert.deepEqual(hrefs(html), [`https://trusted.com/${tokens[0]}`, `https://trusted.com/${tokens[1]}`]);
+ assert.ok(html.includes(`<code>${tokens[2]}</code>`));
+ }
+ });
+
+ test(`${build}: inline code in destinations is escaped attribute text while labels keep code markup`, () => {
+ const code = '" style="background-image:url(https://tracker.com/inline-destination)';
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ const html = render(`[label \`visible code\`](https://trusted.com/\`${code}\`)`, { enhance: false });
+ assert.deepEqual(hrefs(html), [`https://trusted.com/${code.replace(/"/g, '&quot;')}`]);
+ assert.match(html, />label <code>visible code<\/code><\/a>/);
+ assert.equal((html.match(/<code>/g) || []).length, 1);
+ }
+ });
+
+ test(`${build}: every streamed image prefix keeps its URLs out of favicon discovery`, () => {
+ const images = [
+ '![private](https://private.customer.com/secret)',
+ '![**private**](https://private.customer.com/secret_(nested_(value)))',
+ '![https://private.customer.com/label](https://private.customer.com/image)',
+ ];
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ for (const image of images) {
+ for (let length = 1; length <= image.length; length++) {
+ const html = render(image.slice(0, length), { enhance: false, recoverNestedMarkdown: true });
+ assert.doesNotMatch(html, /<img\b/);
+ for (const anchor of anchorTags(html)) {
+ assert.match(anchor, /\bdata-no-favicon(?:=|\s|>)/, `image prefix ${JSON.stringify(image.slice(0, length))}`);
+ }
+ }
+ }
+ }
+ });
+
+ test(`${build}: completed images and literal image syntax in code do not hide following links`, () => {
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ for (const before of ['![private](https://private.customer.com/image)', '`![private`', '```text\n![private\n```']) {
+ const html = render(`${before}\n\nhttps://public.customer.com/article`, { enhance: false });
+ const eligible = anchorTags(html).filter(anchor => !/\bdata-no-favicon(?:=|\s|>)/.test(anchor));
+ assert.equal(eligible.length, 1, `following ordinary link stays eligible after ${before}`);
+ assert.match(eligible[0], /href="https:\/\/public\.customer\.com\/article"/);
+ }
+ }
+ });
+
+ test(`${build}: live and restored chat preserve wildcard destinations and code`, () => {
+ const source = 'https://example.com/path/*wildcard* [Docs](https://example.com/docs/*wildcard*) ![Image](https://example.com/image/*wildcard*) `https://code.example/literal`';
+ const expected = ['https://example.com/path/*wildcard*', 'https://example.com/docs/*wildcard*', 'https://example.com/image/*wildcard*'];
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ const html = render(source);
+ assert.deepEqual(hrefs(html), expected);
+ assert.match(html, />https:\/\/example.com\/path\/\*wildcard\*<\/a>/);
+ assert.doesNotMatch(html, /<img\b/);
+ assert.match(html, /<code>https:\/\/code.example\/literal<\/code>/);
+ }
+ });
+
+ test(`${build}: emphasized URLs keep Markdown markers out of their destinations`, () => {
+ for (const render of [formatMarkdown, renderSkillMarkdown]) {
+ for (const source of ['**https://example.com/path**', '*https://example.com/path*', '**See https://example.com/path**']) {
+ const html = render(source);
+ assert.deepEqual(hrefs(html), ['https://example.com/path']);
+ assert.match(html, /<(?:strong|em)>/);
+ assert.doesNotMatch(html, /\*/);
+ }
+ const wildcard = render('**https://example.com/*wildcard***');
+ assert.deepEqual(hrefs(wildcard), ['https://example.com/*wildcard*']);
+ assert.match(wildcard, /<strong><a\b/);
+ }
+ });
+
+ test(`${build}: sidepanel honors Strict Secret Mode before every favicon request`, async () => {
+ const source = readUi(build, 'sidepanel.js');
+ const start = source.indexOf('const disposeChatLinkIcons = installChatLinkIcons(');
+ const end = source.indexOf('\nwindow.addEventListener(\'pagehide\'', start);
+ assert.ok(start >= 0 && end > start);
+ let strictSecretMode = true;
+ let installedOptions;
+ const requests = [];
+ const storage = { local: { get: async key => {
+ assert.equal(key, 'strictSecretMode');
+ return { strictSecretMode };
+ } } };
+ vm.runInNewContext(source.slice(start, end), {
+ messagesEl: {},
+ chrome: { storage }, browser: { storage },
+ installChatLinkIcons(_root, options) { installedOptions = options; return () => {}; },
+ fetch(url, options) { requests.push({ url, options }); return Promise.resolve('mock icon response'); },
+ });
+ const requestOptions = { credentials: 'omit', referrerPolicy: 'no-referrer', redirect: 'error' };
+ await assert.rejects(installedOptions.fetchImpl('https://icons.duckduckgo.com/ip3/google.com.ico', requestOptions), /Strict Secret Mode/);
+ assert.equal(requests.length, 0);
+ strictSecretMode = false;
+ assert.equal(await installedOptions.fetchImpl('https://icons.duckduckgo.com/ip3/google.com.ico', requestOptions), 'mock icon response');
+ assert.equal(requests.length, 1);
+ assert.equal(requests[0].options, requestOptions);
+ strictSecretMode = true;
+ await assert.rejects(installedOptions.fetchImpl('https://icons.duckduckgo.com/ip3/github.com.ico', requestOptions), /Strict Secret Mode/);
+ assert.equal(requests.length, 1, 'a later settings change is checked before issuing another request');
+ });
+
+ if (process.env.WEBBRAIN_CHAT_LINKS_DOM === '1') test(`${build}: native rendering prevents placeholder injection and pending-image network requests`, async () => {
+ const { chromium, firefox } = await import('playwright');
+ const browser = await (build === 'chrome' ? chromium : firefox).launch({ headless: true });
+ try {
+ const context = await browser.newContext({ serviceWorkers: 'block' });
+ const networkRequests = [];
+ context.on('request', request => {
+ if (new URL(request.url()).hostname !== 'chat-links.test') networkRequests.push(request.url());
+ });
+ // Real browser fetches and CSS/image requests are recorded, but every
+ // request is fulfilled locally, including any regression's tracking URL.
+ await context.route('**/*', async route => {
+ const url = new URL(route.request().url());
+ const file = url.pathname.slice(1);
+ if (url.hostname === 'chat-links.test' && /^[\w-]+\.js$/.test(file)) {
+ await route.fulfill({ contentType: 'text/javascript', body: readUi(build, file) });
+ } else if (url.hostname === 'chat-links.test') {
+ await route.fulfill({ contentType: 'text/html', body: '<div id="messages"><div class="message-text" id="content"></div></div>' });
+ } else {
+ await route.fulfill({ status: 404, headers: { 'access-control-allow-origin': '*' }, contentType: 'text/plain', body: '' });
+ }
+ });
+ const page = await context.newPage();
+ await page.goto('http://chat-links.test/');
+ 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 { renderSkillMarkdown } = await import('/skill-markdown.js');
+ const { installChatLinkIcons } = await import('/chat-link-icons.js');
+ const dependencies = { ...helpers, ...links, escapeHtml, t: key => key, scheduleMathRender() {}, setTimeout() {} };
+ window.chatRenderers = {
+ live: new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies)),
+ saved: renderSkillMarkdown,
+ };
+ window.strictSecretModeForTest = true;
+ window.faviconFetchAttempts = [];
+ window.stopSecurityIcons = installChatLinkIcons(document.querySelector('#messages'), {
+ intersectionObserverImpl: null,
+ fetchImpl: (url, options) => {
+ if (window.strictSecretModeForTest) throw new Error('Strict Secret Mode');
+ window.faviconFetchAttempts.push(String(url));
+ return fetch(url, options);
+ },
+ });
+ }, { formatter: formatterSource(build) });
+
+ const injectionResults = await page.evaluate(async () => {
+ const content = document.querySelector('#content');
+ const results = [];
+ for (const [name, render] of Object.entries(window.chatRenderers)) {
+ const tokens = name === 'live'
+ ? ['__CHAT_LINK_1__', '__INLINE_0__', '__CODEBLOCK_0__']
+ : ['__SKILL_LINK_1__', '__SKILL_INLINE_CODE_0__', '__SKILL_CODE_BLOCK_0__'];
+ const payloads = [
+ `[a](https://trusted.com/${tokens[0]}) [b](https://x style=background-image:url(https://tracker.com/secret) x=y)`,
+ '[a](https://trusted.com/WBMD0TOKEN1END) [b](https://x style=background-image:url(https://tracker.com/current-namespace) x=y)',
+ `[a](https://trusted.com/${tokens[1]}) \`" style="background-image:url(https://tracker.com/inline)\``,
+ `[a](https://trusted.com/${tokens[2]})\n\n\`\`\`text\n" style="background-image:url(https://tracker.com/fenced)\n\`\`\``,
+ '[label `visible code`](https://trusted.com/`" style="background-image:url(https://tracker.com/inline-destination)`)',
+ ];
+ for (const payload of payloads) {
+ content.innerHTML = render(payload, { enhance: false });
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ results.push({
+ name, payload,
+ unsafeAttributes: [...content.querySelectorAll('*')].flatMap(element => [...element.attributes]
+ .filter(attribute => /^(?:style|srcdoc|on\w+)$/i.test(attribute.name)).map(attribute => attribute.name)),
+ externalImages: [...content.querySelectorAll('img[src]')].map(image => image.getAttribute('src')).filter(src => !src.startsWith('blob:')),
+ anchors: [...content.querySelectorAll('a')].map(anchor => ({ href: anchor.getAttribute('href'), target: anchor.target, rel: anchor.rel })),
+ code: [...content.querySelectorAll('code')].map(code => code.textContent),
+ });
+ }
+ }
+ return results;
+ });
+ assert.deepEqual(networkRequests, [], 'Strict Secret Mode must not be bypassed through injected CSS or image requests');
+ for (const result of injectionResults) {
+ assert.deepEqual(result.unsafeAttributes, [], `${result.name}: ${result.payload}`);
+ assert.deepEqual(result.externalImages, [], `${result.name}: ${result.payload}`);
+ assert.equal(result.anchors.length, result.payload.includes('[b]') ? 2 : 1);
+ if (result.payload.includes('visible code')) {
+ assert.deepEqual(result.code, ['visible code']);
+ assert.equal(result.anchors[0].href, 'https://trusted.com/" style="background-image:url(https://tracker.com/inline-destination)');
+ }
+ for (const anchor of result.anchors) {
+ assert.equal(anchor.target, '_blank');
+ assert.match(anchor.rel, /\bnoopener\b/);
+ assert.match(anchor.rel, /\bnoreferrer\b/);
+ }
+ }
+
+ const streamedImages = await page.evaluate(async () => {
+ window.strictSecretModeForTest = false;
+ const content = document.querySelector('#content');
+ const images = [
+ '![private](https://private.customer.com/secret)',
+ '![**private**](https://private.customer.com/secret_(nested_(value)))',
+ '![https://private.customer.com/label](https://private.customer.com/image)',
+ ];
+ const decoratedImages = [];
+ const renderers = { ...window.chatRenderers, legacy: source => source };
+ for (const [name, render] of Object.entries(renderers)) {
+ for (const image of images) {
+ for (let length = 1; length <= image.length; length++) {
+ const source = image.slice(0, length);
+ if (name === 'legacy') content.textContent = source;
+ else content.innerHTML = render(source, { enhance: false, recoverNestedMarkdown: true });
+ // Let the real MutationObserver and queued favicon work run
+ // for each prefix before replacing the streamed text again.
+ await new Promise(resolve => setTimeout(resolve, 0));
+ if (content.querySelector('.chat-link-icon, img[src]')) decoratedImages.push({ name, source });
+ }
+ }
+ }
+ for (const legacy of [
+ '![<strong>private</strong>](https://private.customer.com/secret',
+ '![private](<a href="https://private.customer.com/secret">https://private.customer.com/secret</a>',
+ ]) {
+ content.innerHTML = legacy;
+ await new Promise(resolve => setTimeout(resolve, 0));
+ if (content.querySelector('.chat-link-icon, img[src]')) decoratedImages.push({ name: 'legacy split nodes', source: legacy });
+ }
+ await new Promise(resolve => setTimeout(resolve, 50));
+ return { decoratedImages, attempts: window.faviconFetchAttempts };
+ });
+ assert.deepEqual(streamedImages.decoratedImages, [], 'pending and complete image syntax must never receive favicon decoration');
+ assert.deepEqual(streamedImages.attempts, [], 'image prefixes cannot trigger even a partial-host favicon lookup');
+ assert.deepEqual(networkRequests, [], 'actual browser network remains silent throughout streamed image prefixes');
+
+ const controlRequest = page.waitForRequest('https://icons.duckduckgo.com/ip3/public.customer.com.ico');
+ await page.evaluate(() => {
+ document.querySelector('#content').innerHTML = '<pre><code>![literal image syntax</code></pre> Ordinary link https://public.customer.com/article';
+ });
+ await controlRequest;
+ assert.deepEqual(networkRequests, ['https://icons.duckduckgo.com/ip3/public.customer.com.ico'], 'a normal restored URL still exercises the real favicon fetch path');
+ await page.evaluate(() => window.stopSecurityIcons());
+ } finally {
+ await browser.close();
+ }
+ });
+
+ if (process.env.WEBBRAIN_CHAT_LINKS_DOM === '1') test(`${build}: native chat links, favicon privacy, failures and streaming replacements`, async () => {
+ const { chromium, firefox } = await import('playwright');
+ const browser = await (build === 'chrome' ? chromium : firefox).launch({ headless: true });
+ try {
+ const context = await browser.newContext({ viewport: { width: 480, height: 1000 } });
+ // Every browser request is fulfilled locally. Favicon fetching is also
+ // injected below so these checks never contact an outside service.
+ await context.route('**/*', async route => {
+ const url = new URL(route.request().url());
+ const file = url.pathname.slice(1);
+ if (url.hostname === 'chat-links.test' && /^[\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="chat-container"><div id="messages"><div class="message assistant"><div class="message-content"><div id="chat-test-content" class="message-text"></div></div></div></div></div></body></html>' });
+ }
+ });
+ const page = await context.newPage();
+ 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() {} };
+ window.formatChatForTest = new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies));
+ const root = document.querySelector('#chat-test-content');
+ root.innerHTML = window.formatChatForTest([
+ 'https://www.google.com/finance/quote/BZ:NASDAQ?secret=not-an-icon-query',
+ '[Hong Kong](https://www.google.com/finance/quote/2076:HKG)',
+ '[Unavailable icon](https://github.com/project)',
+ '[Invalid icon](https://stackoverflow.com/questions/123)',
+ '[Local](http://127.0.0.1/private)',
+ '[Credentials](https://user:[email protected]/private)',
+ '![Untrusted image](https://tracking.example/pixel?private=value)',
+ '`https://code.example/should-not-fetch`',
+ ].join('\n\n'));
+ const canvas = document.createElement('canvas');
+ canvas.width = 14; canvas.height = 14;
+ const paint = canvas.getContext('2d');
+ paint.fillStyle = '#4285f4'; paint.fillRect(0, 0, 14, 14);
+ paint.fillStyle = '#fff'; paint.font = 'bold 11px sans-serif'; paint.fillText('G', 2, 11);
+ const png = Uint8Array.from(atob(canvas.toDataURL('image/png').split(',')[1]), char => char.charCodeAt(0));
+ window.chatIconRequests = [];
+ window.stopChatLinkIcons = installChatLinkIcons(document.querySelector('#messages'), {
+ intersectionObserverImpl: null,
+ fetchImpl: async (url, options) => {
+ window.chatIconRequests.push({ url: String(url), credentials: options.credentials, referrerPolicy: options.referrerPolicy, redirect: options.redirect });
+ if (String(url).includes('github.com')) return new Response('', { status: 404 });
+ if (String(url).includes('stackoverflow.com')) return new Response('<html>not an image</html>', { headers: { 'content-type': 'text/html' } });
+ return new Response(png, { headers: { 'content-type': 'image/png' } });
+ },
+ });
+ }, { formatter: formatterSource(build) });
+ await page.waitForFunction(() => document.querySelectorAll('#chat-test-content a.chat-link-icon-ready').length === 2);
+ const first = await page.evaluate(() => ({
+ requests: window.chatIconRequests,
+ anchors: [...document.querySelectorAll('#chat-test-content a')].map(anchor => ({
+ href: anchor.href, target: anchor.target, rel: anchor.rel,
+ hasImage: !!anchor.querySelector('img[src]'),
+ ready: anchor.classList.contains('chat-link-icon-ready'),
+ })),
+ unsafeImages: [...document.querySelectorAll('#chat-test-content img[src]')].filter(image => !image.src.startsWith('blob:')).length,
+ displayedText: document.querySelector('#chat-test-content').textContent,
+ }));
+ assert.equal(first.requests.length, 3, 'one bounded request per eligible hostname, including failed icons');
+ for (const request of first.requests) {
+ assert.equal(request.credentials, 'omit');
+ assert.equal(request.referrerPolicy, 'no-referrer');
+ assert.equal(request.redirect, 'error');
+ assert.doesNotMatch(request.url, /secret|private|BZ:|2076:|questions|user:pass|tracking|127\.0\.0\.1|code\.example/);
+ }
+ assert.equal(first.unsafeImages, 0);
+ assert.equal(first.anchors.length, 7);
+ for (const anchor of first.anchors) {
+ assert.equal(anchor.target, '_blank');
+ assert.ok(anchor.rel.split(/\s+/).includes('noopener'));
+ assert.ok(anchor.rel.split(/\s+/).includes('noreferrer'));
+ if (!anchor.href.startsWith('https://www.google.com/')) assert.equal(anchor.ready, false);
+ }
+ assert.match(first.displayedText, /Hong Kong/);
+ assert.doesNotMatch(first.displayedText, /favicon/);
+
+ // Streaming replaces the nodes, so observer decoration must reuse the
+ // cached domain icon while discovering a new link without duplicate UI.
+ await page.evaluate(() => {
+ document.querySelector('#chat-test-content').innerHTML = window.formatChatForTest('https://www.google.com/finance/quote/BZ:NASDAQ\n\nhttps://developer.mozilla.org/docs?private=123', { enhance: false });
+ });
+ await page.waitForFunction(() => document.querySelectorAll('#chat-test-content a.chat-link-icon-ready').length === 2 && window.chatIconRequests.length === 4, null, { timeout: 5000 }).catch(async error => {
+ const state = await page.evaluate(() => ({
+ html: document.querySelector('#chat-test-content').innerHTML,
+ requests: window.chatIconRequests,
+ images: [...document.images].map(image => ({ complete: image.complete, width: image.naturalWidth, src: image.src })),
+ }));
+ throw new Error(`${error.message}\n${JSON.stringify(state)}`);
+ });
+ const after = await page.evaluate(() => ({
+ requests: window.chatIconRequests,
+ iconCount: document.querySelectorAll('#chat-test-content .chat-link-icon').length,
+ links: document.querySelectorAll('#chat-test-content a').length,
+ }));
+ assert.equal(after.links, 2);
+ assert.equal(after.iconCount, 2);
+ assert.equal(after.requests.filter(request => request.url.includes('www.google.com')).length, 1);
+ assert.doesNotMatch(after.requests[3].url, /private|\/docs|\?/);
+
+ await page.evaluate(() => {
+ const legacy = document.createElement('p');
+ legacy.className = 'message-text';
+ legacy.id = 'restored-chat-test';
+ legacy.innerHTML = 'Saved quote https://www.google.com/finance/quote/2076:HKG <code>https://code.example/literal</code> !<a href="https://example.org/legacy-image?secret=private">legacy image</a>';
+ document.querySelector('#chat-test-content').append(legacy);
+ });
+ await page.waitForFunction(() => document.querySelectorAll('#restored-chat-test a.chat-link-icon-ready').length === 1, null, { timeout: 5000 });
+ const restored = await page.evaluate(() => ({
+ requests: window.chatIconRequests.length,
+ links: [...document.querySelectorAll('#restored-chat-test a')].map(anchor => ({ href: anchor.href, target: anchor.target, icon: !!anchor.querySelector('.chat-link-icon') })),
+ codeLinkCount: document.querySelectorAll('#restored-chat-test code a').length,
+ }));
+ assert.equal(restored.requests, 4, 'restored text reuses the cached icon and image syntax causes no request');
+ assert.deepEqual(restored.links, [
+ { href: 'https://www.google.com/finance/quote/2076:HKG', target: '_blank', icon: true },
+ { href: 'https://example.org/legacy-image?secret=private', target: '_blank', icon: false },
+ ]);
+ assert.equal(restored.codeLinkCount, 0);
+
+ if (process.env.WEBBRAIN_CHAT_LINKS_SCREENSHOTS) {
+ await page.setViewportSize({ width: 480, height: 620 });
+ await page.evaluate(() => {
+ const user = document.createElement('div');
+ user.className = 'message user';
+ const content = document.createElement('div');
+ content.className = 'message-content';
+ const text = document.createElement('div');
+ text.className = 'message-text';
+ text.innerHTML = window.formatChatForTest('Open the [Google Finance quote](https://www.google.com/finance/quote/BZ:NASDAQ).');
+ content.append(text); user.append(content);
+ document.querySelector('#messages').prepend(user);
+ document.querySelector('#chat-test-content').innerHTML = window.formatChatForTest([
+ "Here's the Google Finance page for Kanzhun (BZ) on Nasdaq:",
+ 'https://www.google.com/finance/quote/BZ:NASDAQ',
+ 'The Hong Kong listing (2076):',
+ 'https://www.google.com/finance/quote/2076:HKG',
+ 'You can also open the [company quote](https://www.google.com/finance/quote/BZ:NASDAQ).',
+ 'If a site icon is unavailable, [the link still works](https://github.com/project).',
+ ].join('\n\n'));
+ });
+ await page.waitForFunction(() => document.querySelectorAll('#chat-test-content a.chat-link-icon-ready').length === 3 && document.querySelector('.message.user a.chat-link-icon-ready'));
+ await page.screenshot({ path: `${process.env.WEBBRAIN_CHAT_LINKS_SCREENSHOTS}/webbrain-chat-links-${build}.png`, fullPage: true, animations: 'disabled' });
+ }
+
+ const popupPromise = page.waitForEvent('popup');
+ await page.locator('#chat-test-content a').first().click();
+ const popup = await popupPromise;
+ await popup.waitForLoadState();
+ assert.equal(page.url(), 'http://chat-links.test/');
+ assert.equal(popup.url(), 'https://www.google.com/finance/quote/BZ:NASDAQ');
+ await page.evaluate(() => window.stopChatLinkIcons());
+ } finally {
+ await browser.close();
+ }
+ });
+}
diff --git a/test/markdown-render.mjs b/test/markdown-render.mjs
index c3e418b2a..9b013bd94 100644
--- a/test/markdown-render.mjs
+++ b/test/markdown-render.mjs
@@ -26,12 +26,12 @@ const preContents = (html) => [...html.matchAll(/<pre><code>([\s\S]*?)<\/code><\
for (const build of ['chrome', 'firefox']) {
const helpers = await import(`../src/${build}/src/ui/markdown-render.js`);
- const { sanitizeMarkdownLinks } = await import(`../src/${build}/src/ui/markdown-link.js`);
+ const { sanitizeMarkdownLinks, linkifyPlainUrls } = await import(`../src/${build}/src/ui/markdown-link.js`);
const { escapeHtml } = await import(`../src/${build}/src/ui/utils.js`);
const { renderSkillMarkdown } = await import(`../src/${build}/src/ui/skill-markdown.js`);
const { historyTextFromElement } = await import(`../src/${build}/src/ui/history-text.js`);
const formatMarkdown = vm.runInNewContext(`(${panelFormatter(build)})`, {
- ...helpers, sanitizeMarkdownLinks, escapeHtml, t: key => key,
+ ...helpers, sanitizeMarkdownLinks, linkifyPlainUrls, escapeHtml, t: key => key,
scheduleMathRender() {}, setTimeout() {},
});
@@ -694,11 +694,11 @@ for (const build of ['chrome', 'firefox']) {
await page.addStyleTag({ content: fs.readFileSync(new URL(`../src/${build}/styles/sidepanel.css`, import.meta.url), 'utf8') });
const result = await page.evaluate(async ({ formatter, terminalRenderer, source, expected }) => {
const helpers = await import('/markdown-render.js');
- const { sanitizeMarkdownLinks } = await import('/markdown-link.js');
+ const { sanitizeMarkdownLinks, linkifyPlainUrls } = await import('/markdown-link.js');
const { escapeHtml } = await import('/utils.js');
const { historyTextFromElement } = await import('/history-text.js');
const { renderSkillMarkdown } = await import('/skill-markdown.js');
- const dependencies = { ...helpers, sanitizeMarkdownLinks, escapeHtml, t: key => key, scheduleMathRender() {} };
+ const dependencies = { ...helpers, sanitizeMarkdownLinks, linkifyPlainUrls, escapeHtml, t: key => key, scheduleMathRender() {} };
const format = new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies));
let copied = null;
Object.defineProperty(navigator, 'clipboard', { value: { writeText: async text => { copied = text; } } });
@@ -719,7 +719,8 @@ for (const build of ['chrome', 'firefox']) {
document,
};
const renderTerminal = new Function(...Object.keys(updateDependencies), `return (${terminalRenderer})`)(...Object.values(updateDependencies));
- const assistantEl = { querySelector: selector => selector === '.message-text' ? message : {} };
+ message.classList.add('message-text');
+ const assistantEl = message.closest('.message');
renderTerminal(assistantEl, source);
const terminalBlocks = message.querySelectorAll('pre').length;
renderTerminal(assistantEl, source, { replace: true });
diff --git a/test/run.js b/test/run.js
index f5f5ee2ec..9ee94dc5a 100644
--- a/test/run.js
+++ b/test/run.js
@@ -22375,9 +22375,9 @@ test('sidepanels wire highlighting and heading rendering into fenced Markdown',
]) {
const panel = fs.readFileSync(path.join(ROOT, panelRel), 'utf8');
const css = fs.readFileSync(path.join(ROOT, cssRel), 'utf8');
- assert.match(panel, /import \{ codeFenceLanguage, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);
+ assert.match(panel, /import \{ codeFenceLanguage, createMarkdownPlaceholders, highlightCode, renderMarkdownBlockquotes, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);
assert.match(panel, /const lang = codeFenceLanguage\(info\);/, `${label}: fenced code should tolerate metadata after its language token`);
- assert.match(panel, /const highlighted = enhance \? highlightCode\(block\.code, block\.lang\) : escapeHtml\(block\.code\);/, `${label}: completed fenced code should be highlighted by its language while live code stays lightweight`);
+ assert.match(panel, /const highlighted = enhance \? highlightCode\(code, lang\) : escapeHtml\(code\);/, `${label}: completed fenced code should be highlighted by its language while live code stays lightweight`);
assert.match(panel, /text = renderMarkdownTables\(text\);\s*text = renderMarkdownBlockquotes\(text\);\s*text = renderMarkdownHeadings\(text\);/, `${label}: pipe tables and quotes must render before headings swallow the following newline`);
assert.match(css, /\.message-content blockquote \{[\s\S]*?border-left: 3px solid var\(--border\);/, `${label}: rendered quotes should be visually distinct`);
assert.match(css, /\.message-content table \{[\s\S]*?border-collapse: collapse;/, `${label}: rendered tables should have readable borders`);