From bc86a60d9e5588d41f400d2e8052c2bb2f2758ba Mon Sep 17 00:00:00 2001 From: Wenhao Date: Fri, 13 Nov 2026 20:50:50 +0800 Subject: [PATCH] fix(snapshot): support full-answer scrolling and stitching for custom web providers --- content-scripts/custom-provider-driver.js | 1199 ++++++++++++++++- modules/custom-providers.js | 2 +- modules/panel-message-contract.js | 20 +- modules/provider-registry.js | 2 +- tests/custom-provider-driver.test.js | 329 +++++ ...tom-providers-registry-and-storage.test.js | 2 +- ...ustom-provider-snapshot-stitch.e2e.test.js | 524 +++++++ 7 files changed, 2070 insertions(+), 8 deletions(-) create mode 100644 tests/e2e/custom-provider-snapshot-stitch.e2e.test.js diff --git a/content-scripts/custom-provider-driver.js b/content-scripts/custom-provider-driver.js index f4371a9..655165c 100644 --- a/content-scripts/custom-provider-driver.js +++ b/content-scripts/custom-provider-driver.js @@ -14,6 +14,7 @@ const MULTI_PANEL_CONTEXT = 'multi-panel'; const MULTI_PANEL_ACTION_RESULT_CONTEXT = 'multi-panel-action-result'; const MULTI_PANEL_PROVIDER_STATUS_CONTEXT = 'multi-panel-provider-status'; + const MULTI_PANEL_SNAPSHOT_CONTEXT = 'multi-panel-snapshot'; const HOST_TO_FRAME = { INJECT_TEXT: 'INJECT_TEXT', @@ -24,6 +25,9 @@ CLEAR_INPUT: 'CLEAR_INPUT', PANELIZE_RESTORE_USER_FOCUS: 'PANELIZE_RESTORE_USER_FOCUS', PANELIZE_CUSTOM_FRAME_PING: 'PANELIZE_CUSTOM_FRAME_PING', + PANELIZE_SNAPSHOT_PREPARE: 'PANELIZE_SNAPSHOT_PREPARE', + PANELIZE_SNAPSHOT_SCROLL: 'PANELIZE_SNAPSHOT_SCROLL', + PANELIZE_SNAPSHOT_RESTORE: 'PANELIZE_SNAPSHOT_RESTORE', }; const FRAME_TO_HOST = { @@ -34,6 +38,7 @@ PANELIZE_TEMP_CHAT_DISABLED: 'PANELIZE_TEMP_CHAT_DISABLED', PANELIZE_CUSTOM_FRAME_PONG: 'PANELIZE_CUSTOM_FRAME_PONG', PANELIZE_CUSTOM_SW_RECOVERED: 'PANELIZE_CUSTOM_SW_RECOVERED', + PANELIZE_SNAPSHOT_STATE: 'PANELIZE_SNAPSHOT_STATE', }; const SW_RECOVERY_QUERY_PARAM = '__panelize_sw_recover'; @@ -2004,6 +2009,1177 @@ } } + // ===== Share Snapshot: Align, Scroll, Stitch & Restore ===== + + const SNAPSHOT_MATCH_KEY_LENGTH = 40; + const SNAPSHOT_MIN_MATCH_KEY_LENGTH = 2; + const SNAPSHOT_MAX_MATCH_CANDIDATES = 50; + const SNAPSHOT_ALIGN_MARGIN_PX = 16; + const SNAPSHOT_PAINT_SETTLE_MS = 100; + const SNAPSHOT_PAINT_TIMEOUT_MS = 400; + const SNAPSHOT_MIN_CONTAINER_HEIGHT_RATIO = 0.3; + const SNAPSHOT_MAX_EDGE_RATIO = 0.4; + const SNAPSHOT_OVERLAY_MIN_WIDTH_RATIO = 0.5; + const SNAPSHOT_EDGE_TOLERANCE_PX = 24; + const SNAPSHOT_MAX_FLOATING_HEIGHT_RATIO = 0.5; + const SNAPSHOT_MAX_SIDE_RAIL_WIDTH_RATIO = 0.45; + const SNAPSHOT_HIDDEN_MASK_PROPERTIES = ['mask-image', '-webkit-mask-image']; + const SNAPSHOT_CLIPPING_OVERFLOW = /^(hidden|clip|auto|scroll|overlay)$/; + const SNAPSHOT_SKIPPED_TEXT_PARENTS = [ + 'script', + 'style', + 'noscript', + 'template', + 'textarea', + 'input', + 'select', + '[contenteditable=""]', + '[contenteditable="true"]', + '[aria-hidden="true"]', + ].join(', '); + const SNAPSHOT_NAVIGATION_PARENTS = + 'nav, aside, [role="navigation"], [role="complementary"], a[href]'; + const SNAPSHOT_USER_TURN_SELECTORS = [ + '[data-message-author-role="user"]', + '[data-testid="user-message"]', + '[data-testid*="user-message" i]', + '[data-role="user"]', + '[data-author="user"]', + '[data-message-role="user"]', + '[data-sender="user"]', + '[data-content="user-message"]', + '[class*="user-bubble"]', + '[class*="user-message"]', + '[class*="items-end"] .message-bubble', + '.chat-content-item-user', + '.chat-user-message', + ].join(', '); + const SNAPSHOT_ALIGN_TOLERANCE_PX = 2; + const SNAPSHOT_RESTORE_ATTEMPTS = 10; + const SNAPSHOT_UNSTICK_PROPERTIES = ['position', 'top', 'right', 'bottom', 'left']; + const SNAPSHOT_HIDE_PSEUDO_ATTRIBUTE = 'data-panelize-snapshot-hide'; + const SNAPSHOT_HIDE_CURSOR_ATTRIBUTE = 'data-panelize-snapshot-cursor'; + const SNAPSHOT_STYLE_RULES = ` + [${SNAPSHOT_HIDE_PSEUDO_ATTRIBUTE}~="before"]::before, + [${SNAPSHOT_HIDE_PSEUDO_ATTRIBUTE}~="after"]::after { visibility: hidden !important; } + [${SNAPSHOT_HIDE_CURSOR_ATTRIBUTE}], [${SNAPSHOT_HIDE_CURSOR_ATTRIBUTE}] *, + [${SNAPSHOT_HIDE_CURSOR_ATTRIBUTE}] *::before, [${SNAPSHOT_HIDE_CURSOR_ATTRIBUTE}] *::after { cursor: none !important; } + `; + const SNAPSHOT_STYLE_ELEMENT_ID = 'panelize-snapshot-style'; + + let snapshotSession = null; + let snapshotStyleSheet = null; + + function getParentOrShadowHost(node) { + if (!node) { + return null; + } + if (node.parentElement) { + return node.parentElement; + } + const root = typeof node.getRootNode === 'function' ? node.getRootNode() : null; + return root && root.host ? root.host : null; + } + + function normalizeSnapshotMatchText(text) { + return String(text || '') + .normalize('NFKC') + .toLowerCase() + .replace(/[\s\u200b-\u200d\u2060\ufeff*_`]+/g, ''); + } + + function getSnapshotMatchKey(prompt) { + return Array.from(normalizeSnapshotMatchText(prompt)) + .slice(0, SNAPSHOT_MATCH_KEY_LENGTH) + .join(''); + } + + function getSnapshotViewport() { + return { + width: window.innerWidth || document.documentElement?.clientWidth || 0, + height: window.innerHeight || document.documentElement?.clientHeight || 0, + }; + } + + function isSnapshotDocumentScroller(element) { + return ( + !element || + element === document.scrollingElement || + element === document.documentElement || + element === document.body + ); + } + + function isSnapshotScrollable(element) { + if (isSnapshotDocumentScroller(element)) { + const scroller = document.scrollingElement || document.documentElement; + return Boolean(scroller) && scroller.scrollHeight > scroller.clientHeight + 1; + } + const overflowY = window.getComputedStyle(element).overflowY; + return /(auto|scroll|overlay)/.test(overflowY) && element.scrollHeight > element.clientHeight + 1; + } + + function isSnapshotElementRendered(element) { + if (typeof element.checkVisibility === 'function') { + return element.checkVisibility(); + } + return true; + } + + function getSnapshotContainerRect(container) { + const viewport = getSnapshotViewport(); + if (isSnapshotDocumentScroller(container)) { + return { left: 0, top: 0, right: viewport.width, bottom: viewport.height }; + } + const rect = container.getBoundingClientRect(); + const left = rect.left + container.clientLeft; + const top = rect.top + container.clientTop; + const box = { + left: Math.max(0, left), + top: Math.max(0, top), + right: Math.min(viewport.width, left + container.clientWidth), + bottom: Math.min(viewport.height, top + container.clientHeight), + }; + for ( + let node = getParentOrShadowHost(container); + node && !isSnapshotDocumentScroller(node); + node = getParentOrShadowHost(node) + ) { + const style = window.getComputedStyle(node); + if ( + !SNAPSHOT_CLIPPING_OVERFLOW.test(style.overflowX) && + !SNAPSHOT_CLIPPING_OVERFLOW.test(style.overflowY) + ) { + continue; + } + const nodeRect = node.getBoundingClientRect(); + const nodeLeft = nodeRect.left + node.clientLeft; + const nodeTop = nodeRect.top + node.clientTop; + box.left = Math.max(box.left, nodeLeft); + box.top = Math.max(box.top, nodeTop); + box.right = Math.min(box.right, nodeLeft + node.clientWidth); + box.bottom = Math.min(box.bottom, nodeTop + node.clientHeight); + } + return box; + } + + function isLargeSnapshotContainer(element) { + const viewport = getSnapshotViewport(); + if (isSnapshotDocumentScroller(element)) { + return true; + } + const rect = getSnapshotContainerRect(element); + return rect.bottom - rect.top >= viewport.height * SNAPSHOT_MIN_CONTAINER_HEIGHT_RATIO; + } + + function getSnapshotScrollTop(container) { + return isSnapshotDocumentScroller(container) ? window.scrollY : container.scrollTop; + } + + function getSnapshotMaxScrollTop(container) { + const scroller = isSnapshotDocumentScroller(container) + ? document.scrollingElement || document.documentElement + : container; + return Math.max(0, scroller.scrollHeight - scroller.clientHeight); + } + + function clampSnapshotScrollTop(container, top) { + return Math.max(0, Math.min(getSnapshotMaxScrollTop(container), Math.round(top))); + } + + function scrollSnapshotContainer(container, top) { + const target = clampSnapshotScrollTop(container, top); + if (isSnapshotDocumentScroller(container)) { + window.scrollTo({ top: target, behavior: 'instant' }); + } else if (typeof container.scrollTo === 'function') { + container.scrollTo({ top: target, behavior: 'instant' }); + } else { + container.scrollTop = target; + } + } + + function findSnapshotScrollContainer(element, main) { + const ancestors = []; + for ( + let node = element; + node && !isSnapshotDocumentScroller(node); + node = getParentOrShadowHost(node) + ) { + if (isSnapshotScrollable(node) && isLargeSnapshotContainer(node)) { + ancestors.push(node); + } + } + if (isSnapshotScrollable(null)) { + ancestors.push(document.scrollingElement || document.documentElement); + } + if (ancestors.includes(main)) { + return main; + } + return ancestors.reduce( + (best, node) => + !best || getSnapshotMaxScrollTop(node) > getSnapshotMaxScrollTop(best) ? node : best, + null + ); + } + + function findMainSnapshotScrollContainer() { + let best = null; + let bestArea = 0; + const candidates = document.body ? querySelectorAllDeep('*', document.body) : []; + for (let i = 0; i < candidates.length; i += 1) { + const element = candidates[i]; + if (!isSnapshotScrollable(element) || !isLargeSnapshotContainer(element)) { + continue; + } + const rect = getSnapshotContainerRect(element); + const area = Math.max(0, rect.right - rect.left) * Math.max(0, rect.bottom - rect.top); + if (area > bestArea) { + best = element; + bestArea = area; + } + } + return best || document.scrollingElement || document.documentElement; + } + + function isSnapshotConversationElement(element) { + if ( + !isSnapshotElementRendered(element) || + (typeof element.closest === 'function' && element.closest(SNAPSHOT_NAVIGATION_PARENTS)) + ) { + return false; + } + for (let node = element; node && node !== document.body; node = getParentOrShadowHost(node)) { + if (window.getComputedStyle(node).position === 'fixed') { + return false; + } + } + return true; + } + + function collectSnapshotTextIndex() { + const segments = []; + let text = ''; + if (!document.body) { + return { segments, text }; + } + const visitedRoots = new Set(); + const walkRoot = (root) => { + if (!root || visitedRoots.has(root)) { + return; + } + visitedRoots.add(root); + const walker = document.createTreeWalker( + root, + NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, + { + acceptNode(node) { + if (node.nodeType === Node.ELEMENT_NODE) { + if ( + typeof node.matches === 'function' && + node.matches(SNAPSHOT_SKIPPED_TEXT_PARENTS) + ) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + } + const parent = node.parentElement || getParentOrShadowHost(node); + if ( + !parent || + (typeof parent.closest === 'function' && parent.closest(SNAPSHOT_SKIPPED_TEXT_PARENTS)) + ) { + return NodeFilter.FILTER_REJECT; + } + return NodeFilter.FILTER_ACCEPT; + }, + } + ); + for (let node = walker.nextNode(); node; node = walker.nextNode()) { + if (node.nodeType === Node.ELEMENT_NODE) { + if (node.shadowRoot) { + walkRoot(node.shadowRoot); + } + continue; + } + const normalized = normalizeSnapshotMatchText(node.nodeValue); + if (normalized) { + segments.push({ node, start: text.length }); + text += normalized; + } + } + }; + walkRoot(document.body); + return { segments, text }; + } + + function findSnapshotSegment(segments, offset) { + let low = 0; + let high = segments.length - 1; + while (low < high) { + const middle = Math.ceil((low + high) / 2); + if (segments[middle].start <= offset) { + low = middle; + } else { + high = middle - 1; + } + } + return segments[low]; + } + + function findSnapshotPromptMatches(prompt, main) { + const key = getSnapshotMatchKey(prompt); + if (Array.from(key).length < SNAPSHOT_MIN_MATCH_KEY_LENGTH) { + return []; + } + const { segments, text } = collectSnapshotTextIndex(); + if (segments.length === 0) { + return []; + } + const candidates = []; + let offset = text.lastIndexOf(key); + for ( + let checked = 0; + offset !== -1 && checked < SNAPSHOT_MAX_MATCH_CANDIDATES; + checked += 1 + ) { + const segment = findSnapshotSegment(segments, offset); + const element = segment.node.parentElement || getParentOrShadowHost(segment.node); + if (element && isSnapshotConversationElement(element)) { + const container = findSnapshotScrollContainer(element, main); + if (container) { + const isUserTurn = + typeof element.closest === 'function' && + Boolean(element.closest(SNAPSHOT_USER_TURN_SELECTORS)); + const rank = + (isUserTurn ? 0 : 4) + + (segment.start === offset ? 0 : 2) + + (container === main ? 0 : 1); + candidates.push({ element, container, rank }); + } + } + offset = offset > 0 ? text.lastIndexOf(key, offset - 1) : -1; + } + return candidates.sort((a, b) => a.rank - b.rank); + } + + function findSnapshotUserTurn(main) { + const elements = document.body + ? querySelectorAllDeep(SNAPSHOT_USER_TURN_SELECTORS, document.body) + : []; + for (let index = elements.length - 1; index >= 0; index -= 1) { + const element = elements[index]; + if (!isSnapshotConversationElement(element)) { + continue; + } + const container = findSnapshotScrollContainer(element, main); + if (container) { + return { element, container }; + } + } + return null; + } + + function deepContains(ancestor, target) { + if (!ancestor || !target) { + return false; + } + for (let node = target; node; node = getParentOrShadowHost(node)) { + if (node === ancestor) { + return true; + } + } + return false; + } + + function isSnapshotScrolledContent(element, container) { + const containingBlock = element.offsetParent; + if (!containingBlock) { + return false; + } + if (isSnapshotDocumentScroller(container)) { + return true; + } + return containingBlock === container || deepContains(container, containingBlock); + } + + function getSnapshotClip(container) { + const rect = getSnapshotContainerRect(container); + const clip = { ...rect }; + const height = rect.bottom - rect.top; + const width = rect.right - rect.left; + if (height <= 0 || width <= 0) { + return clip; + } + const maxEdge = height * SNAPSHOT_MAX_EDGE_RATIO; + const scope = isSnapshotDocumentScroller(container) ? document.body : container; + const candidates = scope ? querySelectorAllDeep('*', scope) : []; + if (!isSnapshotDocumentScroller(container) && document.body) { + const bodyNodes = querySelectorAllDeep('*', document.body); + for (let i = 0; i < bodyNodes.length; i += 1) { + const element = bodyNodes[i]; + if (!deepContains(container, element) && !deepContains(element, container)) { + candidates.push(element); + } + } + } + + const pinBar = (barRect) => { + if (barRect.width < width * SNAPSHOT_OVERLAY_MIN_WIDTH_RATIO || barRect.height <= 0) { + return; + } + if ( + barRect.bottom <= rect.top || + barRect.top >= rect.bottom || + barRect.right <= rect.left || + barRect.left >= rect.right + ) { + return; + } + if ( + barRect.top <= rect.top + SNAPSHOT_EDGE_TOLERANCE_PX && + barRect.bottom - rect.top <= maxEdge + ) { + clip.top = Math.max(clip.top, barRect.bottom); + } else if ( + barRect.bottom >= rect.bottom - SNAPSHOT_EDGE_TOLERANCE_PX && + rect.bottom - barRect.top <= maxEdge + ) { + clip.bottom = Math.min(clip.bottom, barRect.top); + } + }; + + const overlayingBars = new Set(); + const isInOverlayingBar = (element) => { + for (let node = getParentOrShadowHost(element); node; node = getParentOrShadowHost(node)) { + if (overlayingBars.has(node)) { + return true; + } + } + return false; + }; + + for (let i = 0; i < candidates.length; i += 1) { + const element = candidates[i]; + const style = window.getComputedStyle(element); + const position = style.position; + if (position !== 'sticky' && position !== 'fixed' && position !== 'absolute') { + continue; + } + if (style.visibility === 'hidden' || style.display === 'none' || style.opacity === '0') { + continue; + } + if ( + position === 'absolute' && + deepContains(container, element) && + isSnapshotScrolledContent(element, container) + ) { + continue; + } + if (position === 'absolute' && !deepContains(container, element)) { + const elemRect = element.getBoundingClientRect(); + const sample = document.elementFromPoint?.( + Math.round((rect.left + rect.right) / 2), + Math.round(elemRect.top + 1) + ); + if (sample && deepContains(element, sample)) { + overlayingBars.add(element); + } else if (!isInOverlayingBar(element)) { + continue; + } + } + pinBar(element.getBoundingClientRect()); + } + + // Exclude the bottom composer dock (skipping `display: contents` wrappers whose rect is 0x0). + const input = findComposerElement(); + if (input) { + let box = null; + for ( + let node = input; + node && node !== container && !deepContains(node, container); + node = getParentOrShadowHost(node) + ) { + if (window.getComputedStyle(node).display === 'contents') { + continue; + } + const nodeRect = node.getBoundingClientRect(); + if (nodeRect.width <= 0 || nodeRect.height <= 0) { + continue; + } + if (nodeRect.height > maxEdge || nodeRect.width > width + 2) { + break; + } + box = nodeRect; + } + if ( + box && + box.top < clip.bottom && + box.bottom > rect.top + height - maxEdge && + box.right > rect.left && + box.left < rect.right + ) { + clip.bottom = Math.min(clip.bottom, box.top); + } + } + + if (clip.bottom - clip.top < height * (1 - SNAPSHOT_MAX_EDGE_RATIO * 2)) { + return { ...rect }; + } + return { + left: Math.round(clip.left), + top: Math.round(clip.top), + right: Math.round(clip.right), + bottom: Math.round(clip.bottom), + }; + } + + function getSnapshotPinningNode(element, container) { + const outside = !isSnapshotDocumentScroller(container) && !deepContains(container, element); + const containerRect = getSnapshotContainerRect(container); + let pinning = null; + for ( + let node = element; + node && node !== container && node !== document.body && !deepContains(node, container); + node = getParentOrShadowHost(node) + ) { + if (outside) { + pinning = node; + continue; + } + const position = window.getComputedStyle(node).position; + if (position === 'fixed') { + pinning = node; + } else if (position === 'sticky') { + const rect = node.getBoundingClientRect(); + if ( + Math.abs(rect.top - containerRect.top) <= SNAPSHOT_EDGE_TOLERANCE_PX || + Math.abs(rect.bottom - containerRect.bottom) <= SNAPSHOT_EDGE_TOLERANCE_PX + ) { + pinning = node; + } + } else if ( + position === 'absolute' && + !isSnapshotDocumentScroller(container) && + !isSnapshotScrolledContent(node, container) + ) { + pinning = node; + } + } + return pinning; + } + + function isSnapshotPinned(element, container) { + return Boolean(getSnapshotPinningNode(element, container)); + } + + function overlapsSnapshotClip(rect, clip) { + return ( + rect.width > 0 && + rect.height > 0 && + rect.bottom > clip.top && + rect.top < clip.bottom && + rect.right > clip.left && + rect.left < clip.right + ); + } + + function hasSnapshotReadableText(element) { + return /[\p{L}\p{N}]/u.test(element.textContent || ''); + } + + function saveSnapshotInlineStyle(element, property) { + return { + element, + property, + value: element.style.getPropertyValue(property), + priority: element.style.getPropertyPriority(property), + }; + } + + function restoreSnapshotInlineStyles(savedStyles) { + for (const { element, property, value, priority } of [...savedStyles].reverse()) { + if (value) { + element.style.setProperty(property, value, priority); + } else { + element.style.removeProperty(property); + } + } + } + + function installSnapshotStyles() { + try { + if (typeof CSSStyleSheet === 'function' && Array.isArray(document.adoptedStyleSheets)) { + if (!snapshotStyleSheet) { + snapshotStyleSheet = new CSSStyleSheet(); + snapshotStyleSheet.replaceSync(SNAPSHOT_STYLE_RULES); + } + if (!document.adoptedStyleSheets.includes(snapshotStyleSheet)) { + document.adoptedStyleSheets = [...document.adoptedStyleSheets, snapshotStyleSheet]; + } + return; + } + } catch { + // Fallback to + + +
+
+
+
+
${escape(prompt)}
+
${answer}
+
+
+
+
+
+ +
+
+
You're incognito · Exit Incognito
+
+
+
+
+
+
+
+ + +`; +} + +async function waitForServiceWorkerReady(extension) { + await expect + .poll( + async () => { + extension.serviceWorker = + extension.context.serviceWorkers().at(-1) ?? extension.serviceWorker; + return extension.serviceWorker + .evaluate(() => + Boolean( + chrome.storage?.local && + chrome.storage?.sync && + chrome.declarativeNetRequest?.getDynamicRules && + chrome.scripting?.getRegisteredContentScripts + ) + ) + .catch(() => false); + }, + { timeout: 30_000 } + ) + .toBe(true); +} + +async function clickToolbarIcon(extension, page) { + const session = await extension.context.browser().newBrowserCDPSession(); + try { + const url = page.url(); + const { targetInfos } = await session.send('Target.getTargets', { + filter: [{ type: 'tab' }], + }); + const tab = targetInfos.find((info) => info.url === url); + expect(tab, `tab target for ${url}`).toBeTruthy(); + await session.send('Extensions.triggerAction', { + id: extension.extensionId, + targetId: tab.targetId, + }); + } finally { + await session.detach(); + } +} + +function inspectPreview(page) { + return page.evaluate(async () => { + const image = document.getElementById('share-preview'); + await image.decode(); + const grid = document.getElementById('panel-grid').getBoundingClientRect(); + const frames = Array.from(document.querySelectorAll('#panel-grid iframe'), (frame) => { + const rect = frame.getBoundingClientRect(); + return { + left: rect.left - grid.left, + top: rect.top - grid.top, + width: rect.width, + height: rect.height, + }; + }); + return { + src: image.src, + width: image.naturalWidth, + height: image.naturalHeight, + grid: { width: grid.width, height: grid.height }, + frames, + }; + }); +} + +function getPreviewScale(preview, theme = 'light') { + const padding = SNAPSHOT_FRAME_STYLES[theme].paddingX; + return preview.width / (preview.grid.width + padding * 2); +} + +function readPreviewColumn(page, x) { + return page.evaluate(async (colX) => { + const image = document.getElementById('share-preview'); + await image.decode(); + const canvas = document.createElement('canvas'); + canvas.width = image.naturalWidth; + canvas.height = image.naturalHeight; + const ctx = canvas.getContext('2d'); + ctx.drawImage(image, 0, 0); + const data = ctx.getImageData(Math.round(colX), 0, 1, image.naturalHeight).data; + const column = []; + for (let i = 0; i < data.length; i += 4) { + column.push([data[i], data[i + 1], data[i + 2]]); + } + return column; + }, x); +} + +const isNear = (actual, expected, tolerance) => + actual.every((ch, idx) => Math.abs(ch - expected[idx]) <= tolerance); + +function getColorRuns(column, palette, tolerance = 24) { + const entries = Object.entries(palette); + const runs = []; + column.forEach((pixel, y) => { + const name = entries.find(([, color]) => isNear(pixel, color, tolerance))?.[0] || 'other'; + const last = runs[runs.length - 1]; + if (last?.name === name) { + last.length += 1; + } else { + runs.push({ name, start: y, length: 1 }); + } + }); + return runs; +} + +async function readConversationRuns(page, preview, index, frame = {}) { + const scale = getPreviewScale(preview); + const empty = getSnapshotFrameLayout({ + contentWidth: preview.width - Math.round(SNAPSHOT_FRAME_STYLES.light.paddingX * scale) * 2, + contentHeight: 0, + scale, + titleLineCount: 1, + hasSubline: true, + ...frame, + }); + const top = empty.content.y; + const bottom = preview.height - (empty.height - empty.content.y); + const x = empty.content.x + (preview.frames[index].left + FIXTURE_COLUMN_X) * scale; + const column = (await readPreviewColumn(page, x)).slice(top, bottom); + return getColorRuns(column, CONVERSATION_PALETTE).filter((run) => run.length > 3 * scale); +} + +test.describe('Custom Web UI Share Snapshot full-answer stitching', () => { + test.setTimeout(120_000); + + test('stitches full multi-screen answers on a Perplexity-like Custom Web UI panel alongside ChatGPT and restores scroll & DOM styles afterwards', async ({}, testInfo) => { + const fixture = await startFixtureServer((_req, res) => { + res.setHeader('Content-Type', 'text/html; charset=utf-8'); + res.setHeader('X-Frame-Options', 'DENY'); + res.setHeader('Content-Security-Policy', "frame-ancestors 'self'"); + res.end(renderPerplexityLongThreadFixture({ prompt: PROMPT, blocks: BLOCK_COLORS })); + }); + + const fixtureOrigin = `http://127.0.0.1:${fixture.port}`; + const extensionCopy = await createPatchedExtensionCopy((manifest) => { + manifest.host_permissions.push(`${fixtureOrigin}/*`); + }); + + let extension; + try { + extension = await launchExtension({ + extensionPath: extensionCopy.extensionPath, + viewport: { width: 1280, height: 800 }, + args: [UNSAFE_EXTENSION_DEBUGGING], + }); + await waitForServiceWorkerReady(extension); + + await extension.context.route('https://chatgpt.com/**', (route) => + route.fulfill({ + contentType: 'text/html', + body: renderConversationFixture({ + prompt: PROMPT, + blocks: BLOCK_COLORS, + stickyHeading: true, + wideTable: true, + fade: true, + notice: true, + }), + }) + ); + + // Register Perplexity as a Custom Web UI provider via Options + const optionsPage = await extension.context.newPage(); + await optionsPage.goto(extension.extensionUrl('options/options.html')); + await optionsPage.locator('#custom-provider-name').fill('Perplexity'); + await optionsPage.locator('#custom-provider-url').fill(`${fixtureOrigin}/`); + await optionsPage.locator('#custom-provider-add-btn').click(); + + const customRow = optionsPage.locator( + '#provider-list .provider-item[data-custom-provider="true"]' + ); + await expect(customRow).toHaveCount(1); + const customId = await customRow.getAttribute('data-provider-id'); + await optionsPage.close(); + + await extension.serviceWorker.evaluate(async (id) => { + await chrome.storage.sync.set({ + enabledProviders: ['chatgpt', id], + providerOrder: ['chatgpt', id], + multiPanelProviders: ['chatgpt', id], + multiPanelLayout: '1x2', + }); + }, customId); + + const mpPage = await extension.context.newPage(); + await mpPage.goto(extension.extensionUrl('multi-panel/multi-panel.html')); + + await expect(mpPage.locator('#panel-grid .panel-item')).toHaveCount(2); + await expect(mpPage.frameLocator('#panel-grid iframe').nth(0).locator('.user')).toBeVisible(); + await expect(mpPage.frameLocator('#panel-grid iframe').nth(1).locator('.user')).toBeVisible(); + + const readPanelScrollStates = () => + Promise.all( + mpPage + .frames() + .filter((f) => f.url().startsWith('https://chatgpt.com') || f.url().startsWith(fixtureOrigin)) + .map((f) => + f.evaluate(() => { + const thread = document.getElementById('thread'); + return thread + ? { + url: location.origin, + top: Math.round(thread.scrollTop), + max: Math.round(thread.scrollHeight - thread.clientHeight), + } + : null; + }) + ) + ); + + // Ensure both panels start scrolled to the bottom, as in real chat threads + await expect + .poll(async () => { + for (const f of mpPage.frames()) { + if (f.url().startsWith('https://chatgpt.com') || f.url().startsWith(fixtureOrigin)) { + await f.evaluate(() => { + const thread = document.getElementById('thread'); + if (thread) thread.scrollTop = thread.scrollHeight; + }); + } + } + const states = await readPanelScrollStates(); + return ( + states.length === 2 && + states.every((s) => s && s.max > 800 && Math.abs(s.top - s.max) <= 2) + ); + }) + .toBe(true); + + await mpPage.locator('#unified-input').fill(PROMPT); + await mpPage.bringToFront(); + + // Trigger Share Snapshot (`Full answers` default) + await clickToolbarIcon(extension, mpPage); + await expect(mpPage.locator('#share-modal')).toBeVisible(); + await expect(mpPage.locator('#snapshot-progress')).toBeHidden({ timeout: 60_000 }); + await expect(mpPage.locator('.share-mode-btn[data-mode="full"]')).toHaveAttribute( + 'aria-checked', + 'true' + ); + // Neither ChatGPT nor Perplexity fell back to `Current view only`! + await expect(mpPage.locator('#share-capture-notes')).toBeHidden(); + + const preview = await inspectPreview(mpPage); + await mpPage + .locator('#share-preview') + .screenshot({ path: testInfo.outputPath('custom-web-perplexity-stitched.png') }); + + const scale = getPreviewScale(preview); + for (const panelIndex of [0, 1]) { + const runs = await readConversationRuns(mpPage, preview, panelIndex, { hasNote: false }); + const names = runs.map((r) => r.name); + + // Header once, prompt-aligned user bubble, all 5 blocks + unstuck heading & table in exact order! + expect( + names.filter((n) => n !== 'page' && n !== 'other'), + `panel ${panelIndex} sequence` + ).toEqual([ + 'header', + 'user', + 'block0', + 'heading', + 'block1', + 'tableHeader', + 'tableRow', + 'block2', + 'block3', + 'block4', + ]); + + // Zero composer dock, zero incognito notice, zero scroll-to-end button, zero box-shadow halo, zero earlier turn! + expect(names, `panel ${panelIndex}`).not.toContain('earlier'); + expect(names, `panel ${panelIndex}`).not.toContain('composer'); + expect(names, `panel ${panelIndex}`).not.toContain('notice'); + expect(names, `panel ${panelIndex}`).not.toContain('floating'); + expect(names, `panel ${panelIndex}`).not.toContain('fade'); + + for (const run of runs.filter((r) => r.name.startsWith('block'))) { + expect( + Math.abs(run.length - CONVERSATION_COLORS.blockHeight * scale), + `panel ${panelIndex} ${run.name} height` + ).toBeLessThanOrEqual(4 * scale); + } + } + + // Close modal and verify Perplexity scroll position, Scroll-to-end button, and box-shadow are restored + await mpPage.keyboard.press('Escape'); + await expect(mpPage.locator('#share-modal')).toBeHidden(); + + const afterStates = await readPanelScrollStates(); + for (const state of afterStates) { + expect(Math.abs(state.top - state.max)).toBeLessThanOrEqual(2); + } + + const pplxFrame = mpPage.frames().find((f) => f.url().startsWith(fixtureOrigin)); + expect(pplxFrame).toBeTruthy(); + const restoredDom = await pplxFrame.evaluate(() => { + const scrollDown = document.getElementById('scroll-down'); + const halo = document.getElementById('composer-halo'); + return { + scrollDownVisible: getComputedStyle(scrollDown).visibility === 'visible', + haloBoxShadowRestored: getComputedStyle(halo).boxShadow !== 'none', + }; + }); + expect(restoredDom).toEqual({ + scrollDownVisible: true, + haloBoxShadowRestored: true, + }); + } finally { + await extension?.close(); + await extensionCopy.cleanup(); + await fixture.close(); + } + }); +});