From e0d293fdc0e26d43eb423b1cb0fb60327fe0ad5b Mon Sep 17 00:00:00 2001 From: Wenhao Date: Fri, 13 Nov 2026 18:44:52 +0800 Subject: [PATCH] feat(custom-web): support temporary chat toggling and image uploads --- content-scripts/custom-provider-driver.js | 731 +++++++++++++++++- modules/custom-providers.js | 8 +- modules/panel-message-contract.js | 66 +- modules/provider-registry.js | 25 +- multi-panel/multi-panel.js | 128 ++- .../custom-provider-capability-gates.test.js | 282 ++++++- tests/custom-provider-driver.test.js | 449 +++++++++++ ...tom-providers-registry-and-storage.test.js | 17 +- ...-provider-temp-chat-and-images.e2e.test.js | 343 ++++++++ tests/panel-message-contract.test.js | 23 +- 10 files changed, 2009 insertions(+), 63 deletions(-) create mode 100644 tests/e2e/custom-provider-temp-chat-and-images.e2e.test.js diff --git a/content-scripts/custom-provider-driver.js b/content-scripts/custom-provider-driver.js index 26d5118..f4371a9 100644 --- a/content-scripts/custom-provider-driver.js +++ b/content-scripts/custom-provider-driver.js @@ -19,6 +19,8 @@ INJECT_TEXT: 'INJECT_TEXT', INJECT_TEXT_WITH_IMAGES: 'INJECT_TEXT_WITH_IMAGES', TRIGGER_SEND: 'TRIGGER_SEND', + ENABLE_TEMP_CHAT: 'ENABLE_TEMP_CHAT', + DISABLE_TEMP_CHAT: 'DISABLE_TEMP_CHAT', CLEAR_INPUT: 'CLEAR_INPUT', PANELIZE_RESTORE_USER_FOCUS: 'PANELIZE_RESTORE_USER_FOCUS', PANELIZE_CUSTOM_FRAME_PING: 'PANELIZE_CUSTOM_FRAME_PING', @@ -28,6 +30,8 @@ PANELIZE_ACTION_RESULT: 'PANELIZE_ACTION_RESULT', PANELIZE_PROVIDER_LOCATION: 'PANELIZE_PROVIDER_LOCATION', PANELIZE_PROVIDER_USER_INTERACTION: 'PANELIZE_PROVIDER_USER_INTERACTION', + PANELIZE_TEMP_CHAT_ENABLED: 'PANELIZE_TEMP_CHAT_ENABLED', + PANELIZE_TEMP_CHAT_DISABLED: 'PANELIZE_TEMP_CHAT_DISABLED', PANELIZE_CUSTOM_FRAME_PONG: 'PANELIZE_CUSTOM_FRAME_PONG', PANELIZE_CUSTOM_SW_RECOVERED: 'PANELIZE_CUSTOM_SW_RECOVERED', }; @@ -37,6 +41,7 @@ const ACTION_FAILURE_REASONS = { UNSUPPORTED: 'unsupported', CONTROL_NOT_FOUND: 'control-not-found', + PREVIEW_TIMEOUT: 'preview-timeout', INJECTION_ERROR: 'injection-error', }; @@ -1213,10 +1218,651 @@ return composer; } + // ===== Temporary Chat / Incognito Toggle Discovery ===== + + const TEMP_CHAT_EXIT_RE = + /\b(exit|leave|disable|turn\s*off|stop|end|deactivate)\s+(temporary(\s*(chat|session|conversation|mode))?|incognito(\s*mode)?|private\s*(chat|mode|session)|ephemeral(\s*chat)?|ghost\s*mode)\b|(退出|关闭|停用|结束)(临时(对话|聊天|会话|模式)?|无痕(模式|对话|聊天)?|隐身(模式|对话|聊天)?|私密(对话|聊天|模式)?)/i; + + const TEMP_CHAT_ENTER_RE = + /\b(use|enable|turn\s*on|enter|start|activate)\s+(temporary(\s*(chat|session|conversation|mode))?|incognito(\s*mode)?|private\s*(chat|mode|session)|ephemeral(\s*chat)?|ghost\s*mode)\b|(开启|启用|使用|进入)(临时(对话|聊天|会话|模式)?|无痕(模式|对话|聊天)?|隐身(模式|对话|聊天)?|私密(对话|聊天|模式)?)/i; + + const TEMP_CHAT_NEUTRAL_RE = + /\b(temporary[\s_-]*(chat|session|conversation|mode)|incognito([\s_-]*mode)?|private[\s_-]*(chat|mode|session)|ephemeral[\s_-]*chat|ghost[\s_-]*mode)\b|临时(对话|聊天|会话|模式)|无痕(模式|对话|聊天)|隐身(模式|对话|聊天)|私密(对话|聊天|模式)/i; + + let neutralTempChatClickedOnDocument = false; + + function hasUrlOrCookieTempChatActive() { + try { + const search = window.location && typeof window.location.search === 'string' + ? window.location.search + : ''; + if (search) { + const params = new URLSearchParams(search); + if ( + params.get('temporary-chat') === 'true' || + params.get('temporary') === 'true' || + params.get('incognito') === 'true' + ) { + return true; + } + } + } catch { + // Ignore URL parsing errors. + } + try { + const cookieStr = typeof document.cookie === 'string' ? document.cookie : ''; + if (/(?:^|;\s*)pplx\.is-incognito=true(?:;|$)/i.test(cookieStr)) { + return true; + } + } catch { + // Ignore cookie access errors. + } + return false; + } + + function getTempChatCandidateLabel(el) { + const shortText = ((el.textContent || '').trim().length <= 80 ? (el.textContent || '').trim() : ''); + return [ + el.id || '', + el.getAttribute('name') || '', + el.getAttribute('data-testid') || '', + el.getAttribute('aria-label') || '', + el.getAttribute('title') || '', + el.getAttribute('mattooltip') || '', + shortText, + ] + .join(' ') + .trim(); + } + + function isEligibleTempChatControl(el) { + if (!el || el.tagName === 'A') { + return false; + } + if (typeof el.closest === 'function') { + if ( + el.closest( + 'a[href], [data-composer="true"], [role="article"], article, .prose, .markdown' + ) + ) { + return false; + } + } + if (el.tagName === 'INPUT' && el.type === 'checkbox') { + return !el.disabled && el.getAttribute('aria-disabled') !== 'true'; + } + return isButtonEnabled(el); + } + + function inspectTempChatState() { + const candidates = querySelectorAllDeep( + 'button, [role="button"], [role="switch"], input[type="checkbox"]', + document + ).filter(isEligibleTempChatControl); + + for (let i = 0; i < candidates.length; i += 1) { + const el = candidates[i]; + const label = getTempChatCandidateLabel(el); + if (TEMP_CHAT_EXIT_RE.test(label)) { + return { status: 'active', control: el, hasExplicitState: true }; + } + } + + for (let i = 0; i < candidates.length; i += 1) { + const el = candidates[i]; + const label = getTempChatCandidateLabel(el); + if (TEMP_CHAT_ENTER_RE.test(label)) { + return { status: 'inactive', control: el, hasExplicitState: true }; + } + } + + for (let i = 0; i < candidates.length; i += 1) { + const el = candidates[i]; + const label = getTempChatCandidateLabel(el); + if (!TEMP_CHAT_NEUTRAL_RE.test(label)) { + continue; + } + + if (el.tagName === 'INPUT' && el.type === 'checkbox') { + return { + status: el.checked ? 'active' : 'inactive', + control: el, + hasExplicitState: true, + }; + } + + const ariaPressed = el.getAttribute('aria-pressed'); + const ariaChecked = el.getAttribute('aria-checked'); + const dataState = (el.getAttribute('data-state') || '').toLowerCase(); + const dataActive = el.getAttribute('data-active'); + + if ( + ariaPressed === 'true' || + ariaChecked === 'true' || + dataState === 'checked' || + dataState === 'on' || + dataActive === 'true' + ) { + return { status: 'active', control: el, hasExplicitState: true }; + } + + if ( + ariaPressed === 'false' || + ariaChecked === 'false' || + dataState === 'unchecked' || + dataState === 'off' || + dataActive === 'false' + ) { + return { status: 'inactive', control: el, hasExplicitState: true }; + } + + if (el.classList && (el.classList.contains('active') || el.classList.contains('is-active'))) { + return { status: 'active', control: el, hasExplicitState: true }; + } + + if (hasUrlOrCookieTempChatActive()) { + return { status: 'active', control: el, hasExplicitState: true }; + } + + if (neutralTempChatClickedOnDocument) { + return { status: 'active', control: el, hasExplicitState: false }; + } + + return { status: 'inactive', control: el, hasExplicitState: false }; + } + + return { status: 'missing', control: null, hasExplicitState: false }; + } + + function postTempChatStatus(type, providerId) { + if (!providerId) { + return; + } + postToMultiPanelHost({ + type, + provider: providerId, + context: MULTI_PANEL_PROVIDER_STATUS_CONTEXT, + }); + } + + async function handleEnableTempChat(providerId) { + const initial = inspectTempChatState(); + if (initial.status === 'active') { + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_ENABLED, providerId); + return; + } + if (initial.status !== 'inactive' || !initial.control) { + return; + } + + initial.control.click(); + + if (!initial.hasExplicitState) { + neutralTempChatClickedOnDocument = true; + await sleep(60); + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_ENABLED, providerId); + return; + } + + const deadline = Date.now() + 220; + while (Date.now() < deadline) { + await sleep(40); + if (inspectTempChatState().status === 'active') { + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_ENABLED, providerId); + return; + } + } + } + + async function handleDisableTempChat(providerId) { + const initial = inspectTempChatState(); + if (initial.status === 'inactive') { + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_DISABLED, providerId); + return; + } + if (initial.status !== 'active' || !initial.control) { + return; + } + + initial.control.click(); + neutralTempChatClickedOnDocument = false; + + if (!initial.hasExplicitState) { + await sleep(60); + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_DISABLED, providerId); + return; + } + + const deadline = Date.now() + 220; + while (Date.now() < deadline) { + await sleep(40); + if (inspectTempChatState().status !== 'active') { + postTempChatStatus(FRAME_TO_HOST.PANELIZE_TEMP_CHAT_DISABLED, providerId); + return; + } + } + } + + // ===== Generic Image Upload & Attachment Cleanup ===== + + const IMAGE_ACCEPT_HINT_RE = + /image\/|\*\s*\/\s*\*|\.(png|jpe?g|gif|webp|bmp|svg|avif|heic|heif)\b/i; + + const REMOVE_ATTACHMENT_RE = + /\b(remove|delete|discard)\b.*\b(image|file|attachment|photo|upload|media)\b|^remove\s+\S+|\b(remove|delete)[\s_-]*(attachment|image|file|media|upload)\b|(移除|删除)(图片|附件|文件)/i; + + function createFileFromImagePayload(image) { + if (!image || typeof image.dataUrl !== 'string') { + return null; + } + const match = /^data:(image\/[a-zA-Z0-9.+-]+);base64,([\s\S]+)$/.exec(image.dataUrl.trim()); + if (!match) { + return null; + } + try { + const mimeType = typeof image.type === 'string' && image.type.startsWith('image/') + ? image.type + : match[1]; + const cleanBase64 = match[2].replace(/\s+/g, ''); + const binary = atob(cleanBase64); + const bytes = new Uint8Array(binary.length); + for (let i = 0; i < binary.length; i += 1) { + bytes[i] = binary.charCodeAt(i); + } + const fallbackExt = mimeType.split('/')[1]?.replace(/[^a-z0-9]/gi, '') || 'png'; + const safeName = + typeof image.name === 'string' && image.name.trim().length > 0 + ? image.name.trim() + : `image.${fallbackExt}`; + return new File([bytes], safeName, { type: mimeType, lastModified: Date.now() }); + } catch { + return null; + } + } + + function isImageAcceptingFileInput(input) { + if (!input || input.tagName !== 'INPUT' || (input.type || '').toLowerCase() !== 'file') { + return false; + } + if (input.disabled || input.getAttribute('aria-disabled') === 'true') { + return false; + } + const accept = (input.getAttribute('accept') || '').trim(); + if (!accept) { + return true; + } + return IMAGE_ACCEPT_HINT_RE.test(accept); + } + + function findImageFileInput(composer) { + if (composer) { + const scopes = collectComposerScopes(composer); + for (let i = 0; i < scopes.length; i += 1) { + const inputs = querySelectorAllDeep('input[type="file"]', scopes[i].node).filter( + isImageAcceptingFileInput + ); + if (inputs.length > 0) { + const explicitImg = inputs.find((inp) => + IMAGE_ACCEPT_HINT_RE.test(inp.getAttribute('accept') || '') + ); + return explicitImg || inputs[0]; + } + } + } + + const docInputs = querySelectorAllDeep('input[type="file"]', document).filter( + isImageAcceptingFileInput + ); + if (docInputs.length === 0) { + return null; + } + const explicitDocImg = docInputs.find((inp) => + IMAGE_ACCEPT_HINT_RE.test(inp.getAttribute('accept') || '') + ); + return explicitDocImg || docInputs[0]; + } + + function assignFilesToFileInput(fileInput, files) { + if (!fileInput || !Array.isArray(files) || files.length === 0) { + return false; + } + let assigned = false; + try { + const dt = new DataTransfer(); + for (let i = 0; i < files.length; i += 1) { + dt.items.add(files[i]); + } + fileInput.files = dt.files; + assigned = Boolean(fileInput.files && fileInput.files.length === files.length); + } catch { + assigned = false; + } + + if (!assigned) { + try { + Object.defineProperty(fileInput, 'files', { + configurable: true, + value: files, + }); + assigned = true; + } catch { + return false; + } + } + + fileInput.dispatchEvent(new Event('input', { bubbles: true, composed: true })); + fileInput.dispatchEvent(new Event('change', { bubbles: true, composed: true })); + return true; + } + + function queryAcrossComposerScopes(composer, selector) { + if (!composer) { + const fallbackRoot = document.body || document.documentElement; + return fallbackRoot ? querySelectorAllDeep(selector, fallbackRoot) : []; + } + const scopes = collectComposerScopes(composer); + if (scopes.length === 0) { + const fallbackRoot = composer.parentElement || document.body || document.documentElement; + return fallbackRoot ? querySelectorAllDeep(selector, fallbackRoot) : []; + } + const seen = new Set(); + const results = []; + for (let i = 0; i < scopes.length; i += 1) { + const matches = querySelectorAllDeep(selector, scopes[i].node); + for (let j = 0; j < matches.length; j += 1) { + const el = matches[j]; + if (!seen.has(el)) { + seen.add(el); + results.push(el); + } + } + } + return results; + } + + function inspectComposerAttachments(composer) { + const previewImages = queryAcrossComposerScopes(composer, 'img').filter((img) => { + const src = img.getAttribute('src') || ''; + return src.startsWith('blob:') || src.startsWith('data:image/'); + }); + + const buttons = queryAcrossComposerScopes(composer, 'button, [role="button"]'); + let removeCount = 0; + let disabledPreviewCount = 0; + + for (let i = 0; i < buttons.length; i += 1) { + const btn = buttons[i]; + const aria = (btn.getAttribute('aria-label') || '').trim(); + const title = (btn.getAttribute('title') || '').trim(); + const desc = `${aria} ${title}`.trim(); + + if (/^preview\s+\S+/i.test(aria) && (btn.disabled || btn.getAttribute('aria-disabled') === 'true')) { + disabledPreviewCount += 1; + } + if (REMOVE_ATTACHMENT_RE.test(desc)) { + removeCount += 1; + } + } + + const busyIndicators = queryAcrossComposerScopes( + composer, + '[role="progressbar"], [aria-busy="true"], [data-uploading="true"]' + ); + + const count = Math.max(previewImages.length, removeCount); + const pending = disabledPreviewCount > 0 || busyIndicators.length > 0; + return { count, pending }; + } + + async function waitForComposerUploadSettle(composer, baselineCount, expectedAdded, timeoutMs = 5500) { + const targetCount = baselineCount + expectedAdded; + const deadline = Date.now() + timeoutMs; + let bestAdded = 0; + + while (Date.now() < deadline) { + await sleep(45); + const activeComposer = composer && composer.isConnected ? composer : findComposerElement() || composer; + const state = inspectComposerAttachments(activeComposer); + const added = Math.max(0, state.count - baselineCount); + if (added > bestAdded) { + bestAdded = added; + } + if (added >= expectedAdded && !state.pending) { + return { ok: true, addedCount: expectedAdded }; + } + if (state.count >= targetCount && !state.pending) { + return { ok: true, addedCount: expectedAdded }; + } + } + + return { ok: false, addedCount: Math.min(expectedAdded, bestAdded) }; + } + + function buildFileDataTransfer(files) { + try { + const dt = new DataTransfer(); + for (let i = 0; i < files.length; i += 1) { + dt.items.add(files[i]); + } + if (dt.files && dt.files.length === files.length) { + return dt; + } + } catch { + // Fallback shim below for test DOM environments. + } + return { + files, + types: ['Files'], + items: files.map((file) => ({ kind: 'file', type: file.type, getAsFile: () => file })), + getData: () => '', + }; + } + + async function tryPasteOrDropFiles(composer, files) { + if (!composer || files.length === 0) { + return { handled: false, ok: false, addedCount: 0 }; + } + + const baseline = inspectComposerAttachments(composer).count; + try { + composer.focus({ preventScroll: true }); + } catch { + composer.focus(); + } + + const dt = buildFileDataTransfer(files); + + // 1. Try synthetic ClipboardEvent('paste') + let pasteIntercepted = false; + try { + let pasteEvent; + try { + pasteEvent = new ClipboardEvent('paste', { + bubbles: true, + cancelable: true, + composed: true, + clipboardData: dt instanceof DataTransfer ? dt : undefined, + }); + } catch { + pasteEvent = new Event('paste', { bubbles: true, cancelable: true, composed: true }); + } + if (!pasteEvent.clipboardData || !pasteEvent.clipboardData.files || pasteEvent.clipboardData.files.length === 0) { + Object.defineProperty(pasteEvent, 'clipboardData', { + configurable: true, + value: dt, + }); + } + const notCancelled = composer.dispatchEvent(pasteEvent); + pasteIntercepted = !notCancelled || Boolean(pasteEvent.defaultPrevented); + } catch { + pasteIntercepted = false; + } + + if (pasteIntercepted) { + const settled = await waitForComposerUploadSettle(composer, baseline, files.length, 4500); + return { handled: true, ok: settled.ok, addedCount: settled.addedCount }; + } + + await sleep(10); + if (inspectComposerAttachments(composer).count > baseline) { + const settled = await waitForComposerUploadSettle(composer, baseline, files.length, 4500); + return { handled: true, ok: settled.ok, addedCount: settled.addedCount }; + } + + // 2. Try synthetic DragEvent('drop') + let dropIntercepted = false; + try { + let dropEvent; + try { + dropEvent = new DragEvent('drop', { + bubbles: true, + cancelable: true, + composed: true, + dataTransfer: dt instanceof DataTransfer ? dt : undefined, + }); + } catch { + dropEvent = new Event('drop', { bubbles: true, cancelable: true, composed: true }); + } + if (!dropEvent.dataTransfer || !dropEvent.dataTransfer.files || dropEvent.dataTransfer.files.length === 0) { + Object.defineProperty(dropEvent, 'dataTransfer', { + configurable: true, + value: dt, + }); + } + const notCancelled = composer.dispatchEvent(dropEvent); + dropIntercepted = !notCancelled || Boolean(dropEvent.defaultPrevented); + } catch { + dropIntercepted = false; + } + + if (dropIntercepted) { + const settled = await waitForComposerUploadSettle(composer, baseline, files.length, 4500); + return { handled: true, ok: settled.ok, addedCount: settled.addedCount }; + } + + await sleep(10); + if (inspectComposerAttachments(composer).count > baseline) { + const settled = await waitForComposerUploadSettle(composer, baseline, files.length, 4500); + return { handled: true, ok: settled.ok, addedCount: settled.addedCount }; + } + + return { handled: false, ok: false, addedCount: 0 }; + } + + async function uploadImagesToComposer(composer, images) { + const entries = []; + for (let i = 0; i < images.length; i += 1) { + const img = images[i]; + const file = createFileFromImagePayload(img); + if (!file) { + return { + ok: false, + reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, + succeededImageIds: [], + }; + } + entries.push({ id: img.id, file }); + } + + const fileInput = findImageFileInput(composer); + if (fileInput) { + if (entries.length === 1 || fileInput.multiple) { + const baseline = inspectComposerAttachments(composer).count; + const files = entries.map((entry) => entry.file); + if (!assignFilesToFileInput(fileInput, files)) { + return { + ok: false, + reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, + succeededImageIds: [], + }; + } + const settled = await waitForComposerUploadSettle(composer, baseline, entries.length, 5500); + const succeededImageIds = entries + .slice(0, settled.addedCount) + .map((entry) => entry.id) + .filter((id) => typeof id === 'string'); + return settled.ok + ? { ok: true, succeededImageIds } + : { + ok: false, + reason: ACTION_FAILURE_REASONS.PREVIEW_TIMEOUT, + succeededImageIds, + }; + } + + // Single-file input with multiple images: upload sequentially + const succeededImageIds = []; + for (let i = 0; i < entries.length; i += 1) { + const currentInput = findImageFileInput(composer) || fileInput; + const baseline = inspectComposerAttachments(composer).count; + if (!assignFilesToFileInput(currentInput, [entries[i].file])) { + return { + ok: false, + reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, + succeededImageIds, + }; + } + const settled = await waitForComposerUploadSettle(composer, baseline, 1, 5500); + if (!settled.ok) { + return { + ok: false, + reason: ACTION_FAILURE_REASONS.PREVIEW_TIMEOUT, + succeededImageIds, + }; + } + if (typeof entries[i].id === 'string') { + succeededImageIds.push(entries[i].id); + } + } + return { ok: true, succeededImageIds }; + } + + // No in DOM: attempt paste/drop on composer + const fallback = await tryPasteOrDropFiles(composer, entries.map((entry) => entry.file)); + if (!fallback.handled) { + return { + ok: false, + reason: ACTION_FAILURE_REASONS.UNSUPPORTED, + succeededImageIds: [], + }; + } + + const succeededImageIds = entries + .slice(0, fallback.addedCount) + .map((entry) => entry.id) + .filter((id) => typeof id === 'string'); + return fallback.ok + ? { ok: true, succeededImageIds } + : { + ok: false, + reason: ACTION_FAILURE_REASONS.PREVIEW_TIMEOUT, + succeededImageIds, + }; + } + + function clearComposerAttachments(composer) { + const buttons = queryAcrossComposerScopes(composer, 'button, [role="button"]'); + let removed = 0; + for (let i = 0; i < buttons.length; i += 1) { + const btn = buttons[i]; + if (!isButtonEnabled(btn)) { + continue; + } + const desc = `${btn.getAttribute('aria-label') || ''} ${btn.getAttribute('title') || ''}`.trim(); + if (REMOVE_ATTACHMENT_RE.test(desc)) { + btn.click(); + removed += 1; + } + } + return removed; + } + // ===== Message Dispatch ===== async function handleFillWithResult(eventData, providerId) { const { text, images, autoSubmit, requestId, retry = false } = eventData; + const hasImages = Array.isArray(images) && images.length > 0; + const hasText = typeof text === 'string' && text.length > 0; if (requestId && providerId) { startUserInteractionTracking(requestId, providerId); @@ -1224,24 +1870,16 @@ stopUserInteractionTracking(); } - // Custom generic driver does not upload images; inject text if provided and - // return 'unsupported' immediately so the host never stalls on its preview timer. - if (Array.isArray(images) && images.length > 0) { - if (typeof text === 'string' && text.length > 0 && text.length <= MAX_TEXT_BYTES) { - const composer = await findComposerWithRetry(500); - if (composer) { - await injectTextIntoComposer(composer, text, { skipIfAlreadyPresent: Boolean(retry) }); - } - } + if (typeof text === 'string' && text.length > MAX_TEXT_BYTES) { postActionResult(requestId, providerId, { ok: false, - reason: ACTION_FAILURE_REASONS.UNSUPPORTED, + reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, succeededImageIds: [], }); return; } - if (typeof text !== 'string' || text.length === 0 || text.length > MAX_TEXT_BYTES) { + if (!hasImages && !hasText) { postActionResult(requestId, providerId, { ok: false, reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, @@ -1250,7 +1888,7 @@ return; } - const composer = await findComposerWithRetry(1000); + const composer = await findComposerWithRetry(hasImages ? 600 : 1000); if (!composer) { postActionResult(requestId, providerId, { ok: false, @@ -1260,26 +1898,60 @@ return; } - const injected = await injectTextIntoComposer(composer, text, { - skipIfAlreadyPresent: Boolean(retry), - }); - if (!injected) { - postActionResult(requestId, providerId, { - ok: false, - reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, - succeededImageIds: [], + let succeededImageIds = []; + if (hasImages) { + const uploadResult = await uploadImagesToComposer(composer, images); + succeededImageIds = uploadResult.succeededImageIds || []; + if (!uploadResult.ok) { + if (hasText) { + const refreshedComposer = composer.isConnected ? composer : findComposerElement(); + if (refreshedComposer) { + await injectTextIntoComposer(refreshedComposer, text, { + skipIfAlreadyPresent: Boolean(retry), + }); + } + } + postActionResult(requestId, providerId, { + ok: false, + reason: uploadResult.reason || ACTION_FAILURE_REASONS.INJECTION_ERROR, + succeededImageIds, + }); + return; + } + } + + if (hasText) { + const activeComposer = composer.isConnected ? composer : await findComposerWithRetry(500); + if (!activeComposer) { + postActionResult(requestId, providerId, { + ok: false, + reason: ACTION_FAILURE_REASONS.CONTROL_NOT_FOUND, + succeededImageIds, + }); + return; + } + const injected = await injectTextIntoComposer(activeComposer, text, { + skipIfAlreadyPresent: Boolean(retry), }); - return; + if (!injected) { + postActionResult(requestId, providerId, { + ok: false, + reason: ACTION_FAILURE_REASONS.INJECTION_ERROR, + succeededImageIds, + }); + return; + } } if (autoSubmit === true) { await sleep(80); - await triggerSendWithSettle(composer, { waitForEnabledMs: 700 }); + const activeComposer = composer.isConnected ? composer : findComposerElement(); + await triggerSendWithSettle(activeComposer, { waitForEnabledMs: 700 }); } postActionResult(requestId, providerId, { ok: true, - succeededImageIds: [], + succeededImageIds, }); } @@ -1366,9 +2038,22 @@ return; } + if (type === HOST_TO_FRAME.ENABLE_TEMP_CHAT && context === MULTI_PANEL_CONTEXT) { + void handleEnableTempChat(providerId); + return; + } + + if (type === HOST_TO_FRAME.DISABLE_TEMP_CHAT && context === MULTI_PANEL_CONTEXT) { + void handleDisableTempChat(providerId); + return; + } + if (type === HOST_TO_FRAME.CLEAR_INPUT && context === MULTI_PANEL_CONTEXT) { stopUserInteractionTracking(); const composer = findComposerElement(); + if (event.data.clearImages === true) { + clearComposerAttachments(composer); + } if (composer) { clearComposer(composer); } diff --git a/modules/custom-providers.js b/modules/custom-providers.js index c55ee43..8d209a7 100644 --- a/modules/custom-providers.js +++ b/modules/custom-providers.js @@ -27,7 +27,7 @@ export const CUSTOM_PROVIDER_COOKIE_CONSENT_SCRIPT = export const CUSTOM_API_PANEL_PATH = 'api-panel/api-panel.html'; const CUSTOM_CAPABILITIES = Object.freeze({ - imageUpload: false, + imageUpload: true, inPageNewChat: false, snapshotStitch: false }); @@ -432,7 +432,11 @@ export function toCustomProviderDescriptor(record, { extensionOrigin = null } = id: record.frameRuleId, urlFilter: `|${origin}/` }), - tempChat: null, + tempChat: Object.freeze({ + url: null, + normalUrl: normalizedUrl, + retry: true + }), capabilities: CUSTOM_CAPABILITIES }); } diff --git a/modules/panel-message-contract.js b/modules/panel-message-contract.js index d05ad92..52ea220 100644 --- a/modules/panel-message-contract.js +++ b/modules/panel-message-contract.js @@ -45,7 +45,10 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ 'context' ], senderFiles: ['multi-panel/multi-panel.js', 'modules/panel-action-results.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] }), freezeContractEntry({ type: 'INJECT_TEXT_WITH_IMAGES', @@ -63,7 +66,10 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ 'context' ], senderFiles: ['multi-panel/multi-panel.js', 'modules/panel-action-results.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] }), freezeContractEntry({ type: 'TRIGGER_SEND', @@ -71,7 +77,10 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ direction: 'host-to-frame', payloadFields: ['type', 'requestId', 'providerMode', 'context'], senderFiles: ['multi-panel/multi-panel.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] }), freezeContractEntry({ type: 'NEW_CHAT', @@ -87,7 +96,18 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ direction: 'host-to-frame', payloadFields: ['type', 'providerMode', 'context'], senderFiles: ['multi-panel/multi-panel.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] + }), + freezeContractEntry({ + type: 'DISABLE_TEMP_CHAT', + action: null, + direction: 'host-to-frame', + payloadFields: ['type', 'providerMode', 'context'], + senderFiles: ['multi-panel/multi-panel.js'], + receiverFiles: ['content-scripts/custom-provider-driver.js'] }), freezeContractEntry({ type: 'CLEAR_INPUT', @@ -95,7 +115,10 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ direction: 'host-to-frame', payloadFields: ['type', 'clearImages', 'providerMode', 'context'], senderFiles: ['multi-panel/multi-panel.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] }), freezeContractEntry({ type: 'PANELIZE_RESTORE_USER_FOCUS', @@ -103,7 +126,10 @@ export const HOST_TO_FRAME_MESSAGES = Object.freeze([ direction: 'host-to-frame', payloadFields: ['type', 'context'], senderFiles: ['multi-panel/multi-panel.js'], - receiverFiles: ['content-scripts/text-injection-all-providers.js'] + receiverFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ] }), freezeContractEntry({ type: 'PANELIZE_SNAPSHOT_PREPARE', @@ -156,7 +182,10 @@ export const FRAME_TO_HOST_MESSAGES = Object.freeze([ 'succeededImageIds', 'reason' ], - senderFiles: ['content-scripts/text-injection-all-providers.js'], + senderFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ], receiverFiles: ['modules/panel-action-results.js'] }), freezeContractEntry({ @@ -164,7 +193,10 @@ export const FRAME_TO_HOST_MESSAGES = Object.freeze([ action: null, direction: 'frame-to-host', payloadFields: ['type', 'provider', 'url', 'context'], - senderFiles: ['content-scripts/text-injection-all-providers.js'], + senderFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ], receiverFiles: ['multi-panel/multi-panel.js'] }), freezeContractEntry({ @@ -196,7 +228,10 @@ export const FRAME_TO_HOST_MESSAGES = Object.freeze([ action: null, direction: 'frame-to-host', payloadFields: ['type', 'requestId', 'provider', 'phase', 'context'], - senderFiles: ['content-scripts/text-injection-all-providers.js'], + senderFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ], receiverFiles: ['multi-panel/multi-panel.js'] }), freezeContractEntry({ @@ -204,7 +239,18 @@ export const FRAME_TO_HOST_MESSAGES = Object.freeze([ action: null, direction: 'frame-to-host', payloadFields: ['type', 'provider', 'context'], - senderFiles: ['content-scripts/text-injection-all-providers.js'], + senderFiles: [ + 'content-scripts/text-injection-all-providers.js', + 'content-scripts/custom-provider-driver.js' + ], + receiverFiles: ['multi-panel/multi-panel.js'] + }), + freezeContractEntry({ + type: 'PANELIZE_TEMP_CHAT_DISABLED', + action: null, + direction: 'frame-to-host', + payloadFields: ['type', 'provider', 'context'], + senderFiles: ['content-scripts/custom-provider-driver.js'], receiverFiles: ['multi-panel/multi-panel.js'] }), freezeContractEntry({ diff --git a/modules/provider-registry.js b/modules/provider-registry.js index 3ebef8d..ecda756 100644 --- a/modules/provider-registry.js +++ b/modules/provider-registry.js @@ -19,7 +19,7 @@ const DEFAULT_BUILTIN_CAPABILITIES = Object.freeze({ }); const DEFAULT_CUSTOM_CAPABILITIES = Object.freeze({ - imageUpload: false, + imageUpload: true, inPageNewChat: false, snapshotStitch: false }); @@ -577,12 +577,13 @@ export function validateProviderDescriptor( } } - if (isCustom && descriptor.tempChat !== null) { - errors.push(`Provider "${id || ''}": custom provider tempChat must be null`); + if (isCustomApi && descriptor.tempChat !== null) { + errors.push(`Provider "${id || ''}": custom API provider tempChat must be null`); } else if (descriptor.tempChat !== null && descriptor.tempChat !== undefined) { const tc = descriptor.tempChat; if ( typeof tc !== 'object' || + Array.isArray(tc) || (tc.url !== null && tc.url !== undefined && !isHttpOrHttpsUrl(tc.url)) || !isHttpOrHttpsUrl(tc.normalUrl) || typeof tc.retry !== 'boolean' @@ -590,6 +591,24 @@ export function validateProviderDescriptor( errors.push( `Provider "${id || ''}": tempChat must have nullable http(s) url, http(s) normalUrl, and boolean retry` ); + } else if (isCustom) { + if ((tc.url === null || tc.url === undefined) && tc.retry !== true) { + errors.push( + `Provider "${id || ''}": custom provider non-URL tempChat must specify retry: true` + ); + } + if (customOrigin !== null) { + if (new URL(tc.normalUrl).origin !== customOrigin) { + errors.push( + `Provider "${id || ''}": custom provider tempChat.normalUrl origin must match frameOrigins[0]` + ); + } + if (tc.url && new URL(tc.url).origin !== customOrigin) { + errors.push( + `Provider "${id || ''}": custom provider tempChat.url origin must match frameOrigins[0]` + ); + } + } } } diff --git a/multi-panel/multi-panel.js b/multi-panel/multi-panel.js index 4b26fc7..7416f34 100644 --- a/multi-panel/multi-panel.js +++ b/multi-panel/multi-panel.js @@ -156,6 +156,9 @@ let sendFocusHardTimeoutIds = new Map(); let tempChatRetryTimerIds = new Map(); let tempChatCleanupTimerId = null; let tempChatPendingPanelIds = new Set(); +let tempChatDeactivationRetryTimerIds = new Map(); +let tempChatDeactivationCleanupTimerId = null; +let tempChatDeactivationPendingPanelIds = new Set(); let tempChatButtonRestoreTimerId = null; let isTemporaryChatModeEnabled = false; let customApiHostBridge = null; @@ -235,9 +238,11 @@ const PANELIZE_PROVIDER_BUSY = 'PANELIZE_PROVIDER_BUSY'; const PANELIZE_PROVIDER_IDLE = 'PANELIZE_PROVIDER_IDLE'; const PANELIZE_PROVIDER_USER_INTERACTION = 'PANELIZE_PROVIDER_USER_INTERACTION'; const PANELIZE_TEMP_CHAT_ENABLED = 'PANELIZE_TEMP_CHAT_ENABLED'; +const PANELIZE_TEMP_CHAT_DISABLED = 'PANELIZE_TEMP_CHAT_DISABLED'; const PANELIZE_PROVIDER_LOCATION = 'PANELIZE_PROVIDER_LOCATION'; const PANELIZE_PAGE_WIDTH = 'PANELIZE_PAGE_WIDTH'; const TEMP_CHAT_RETRY_DELAYS = [1200, 2500, 4000]; +const CUSTOM_TEMP_CHAT_RETRY_DELAYS = [150, 800, 2000]; const TEMP_CHAT_OPERATION_TIMEOUT_MS = 5000; let isInitialized = false; @@ -912,6 +917,49 @@ function cancelTemporaryChatActivation({ restoreButton = true } = {}) { } } +function clearTemporaryChatDeactivationRetriesForPanel(panelId) { + const timerIds = tempChatDeactivationRetryTimerIds.get(panelId) || []; + timerIds.forEach(timerId => clearTimeout(timerId)); + tempChatDeactivationRetryTimerIds.delete(panelId); +} + +function cancelTemporaryChatDeactivation() { + tempChatDeactivationRetryTimerIds.forEach((timerIds) => { + timerIds.forEach(timerId => clearTimeout(timerId)); + }); + tempChatDeactivationRetryTimerIds.clear(); + tempChatDeactivationPendingPanelIds.clear(); + + if (typeof tempChatDeactivationCleanupTimerId === 'number') { + clearTimeout(tempChatDeactivationCleanupTimerId); + } + tempChatDeactivationCleanupTimerId = null; +} + +function startTemporaryChatDeactivationCycle() { + cancelTemporaryChatDeactivation(); + tempChatDeactivationCleanupTimerId = setTimeout(() => { + cancelTemporaryChatDeactivation(); + }, TEMP_CHAT_OPERATION_TIMEOUT_MS); +} + +function startTemporaryChatDeactivationForPanel(panel) { + if ( + !panel || + !isCustomWebProvider(panel.providerId) || + !tempChatDeactivationPendingPanelIds.has(panel.id) || + !panel.iframe || + !panel.iframe.contentWindow + ) { + return; + } + + clearTemporaryChatDeactivationRetriesForPanel(panel.id); + CUSTOM_TEMP_CHAT_RETRY_DELAYS.forEach(delay => + scheduleTemporaryChatDeactivationRetry(panel, delay) + ); +} + function startTemporaryChatActivationForPanel(panel) { if (!panel || !requiresTemporaryChatActivationRetry(panel.providerId) || !panel.iframe || !panel.iframe.contentWindow) { return; @@ -919,7 +967,10 @@ function startTemporaryChatActivationForPanel(panel) { clearTemporaryChatRetriesForPanel(panel.id); tempChatPendingPanelIds.add(panel.id); - TEMP_CHAT_RETRY_DELAYS.forEach(delay => scheduleTemporaryChatRetry(panel, delay)); + const retryDelays = isCustomWebProvider(panel.providerId) + ? CUSTOM_TEMP_CHAT_RETRY_DELAYS + : TEMP_CHAT_RETRY_DELAYS; + retryDelays.forEach(delay => scheduleTemporaryChatRetry(panel, delay)); } function startTemporaryChatActivationCycle() { @@ -1127,7 +1178,8 @@ function handleProviderStatusMessage(event) { return; } - const isTempChatMessage = data.type === PANELIZE_TEMP_CHAT_ENABLED; + const isTempChatMessage = + data.type === PANELIZE_TEMP_CHAT_ENABLED || data.type === PANELIZE_TEMP_CHAT_DISABLED; const isLocationMessage = data.type === PANELIZE_PROVIDER_LOCATION; const isPageWidthMessage = data.type === PANELIZE_PAGE_WIDTH; if (data.context !== MULTI_PANEL_PROVIDER_STATUS_CONTEXT @@ -1188,6 +1240,13 @@ function handleProviderStatusMessage(event) { clearTemporaryChatRetriesForPanel(panel.id); tempChatPendingPanelIds.delete(panel.id); break; + case PANELIZE_TEMP_CHAT_DISABLED: + if (!tempChatDeactivationPendingPanelIds.has(panel.id)) { + return; + } + clearTemporaryChatDeactivationRetriesForPanel(panel.id); + tempChatDeactivationPendingPanelIds.delete(panel.id); + break; default: break; } @@ -1668,6 +1727,12 @@ async function addPanel(providerId, { saveConfig = true } = {}) { const livePanel = panels.find(p => p.id === panelId); if (isTemporaryChatModeEnabled && livePanel && requiresTemporaryChatActivationRetry(livePanel.providerId)) { startTemporaryChatActivationForPanel(livePanel); + } else if ( + !isTemporaryChatModeEnabled && + livePanel && + tempChatDeactivationPendingPanelIds.has(livePanel.id) + ) { + startTemporaryChatDeactivationForPanel(livePanel); } setTimeout(() => { loadingPanelIds.delete(panelId); @@ -2029,7 +2094,30 @@ export async function broadcastMessage(text, autoSubmit = true) { ).finally(releaseFocusTracking); }) ); - const normalizedResults = normalizePanelResults(panelResults, targetPanels); + const rawNormalizedResults = normalizePanelResults(panelResults, targetPanels); + const runtimeUnsupportedPanels = []; + const normalizedResults = hasImages + ? rawNormalizedResults.map(result => { + if ( + result && + !result.ok && + result.reason === 'unsupported' && + isCustomWebProvider(result.provider) + ) { + const panel = panels.find(candidate => candidate.id === result.panelId); + if (panel && !imageSkippedPanels.some(skipped => skipped.id === panel.id)) { + runtimeUnsupportedPanels.push(panel); + } + return { + ok: true, + panelId: result.panelId, + provider: result.provider, + succeededImageIds: [] + }; + } + return result; + }) + : rawNormalizedResults; if (hasImages) { if (fillPayloadRevision !== payloadRevisionAtStart) { @@ -2042,8 +2130,9 @@ export async function broadcastMessage(text, autoSubmit = true) { return; } - if (imageSkippedPanels.length > 0) { - const skippedNames = imageSkippedPanels.map( + const allImageSkippedPanels = [...imageSkippedPanels, ...runtimeUnsupportedPanels]; + if (allImageSkippedPanels.length > 0) { + const skippedNames = allImageSkippedPanels.map( panel => getProviderById(panel.providerId)?.name || panel.providerId ); showToast( @@ -3140,14 +3229,42 @@ function scheduleTemporaryChatRetry(panel, delay) { tempChatRetryTimerIds.set(panel.id, timerIds); } +function scheduleTemporaryChatDeactivationRetry(panel, delay) { + const timerId = setTimeout(() => { + if ( + isTemporaryChatModeEnabled || + !tempChatDeactivationPendingPanelIds.has(panel.id) || + !panel.iframe || + !panel.iframe.contentWindow + ) { + return; + } + + focusUnifiedInput({ force: true }); + postToPanelFrame(panel, { + type: 'DISABLE_TEMP_CHAT', + providerMode: getPanelProviderMode(panel), + context: 'multi-panel' + }); + }, delay); + + const timerIds = tempChatDeactivationRetryTimerIds.get(panel.id) || []; + timerIds.push(timerId); + tempChatDeactivationRetryTimerIds.set(panel.id, timerIds); +} + async function temporaryChatAllProviders() { if (isTemporaryChatModeEnabled) { cancelTemporaryChatActivation({ restoreButton: false }); + startTemporaryChatDeactivationCycle(); setTemporaryChatModeEnabled(false); setTemporaryChatButtonDisabled(true); panels.forEach(panel => { if (isTemporaryChatSupportedProvider(panel.providerId)) { + if (isCustomWebProvider(panel.providerId)) { + tempChatDeactivationPendingPanelIds.add(panel.id); + } reloadPanelIframe(panel, getTemporaryChatNormalUrl(panel.providerId)); return; } @@ -3162,6 +3279,7 @@ async function temporaryChatAllProviders() { return; } + cancelTemporaryChatDeactivation(); setTemporaryChatModeEnabled(true); startTemporaryChatActivationCycle(); diff --git a/tests/custom-provider-capability-gates.test.js b/tests/custom-provider-capability-gates.test.js index a34cc4d..a966452 100644 --- a/tests/custom-provider-capability-gates.test.js +++ b/tests/custom-provider-capability-gates.test.js @@ -3,8 +3,13 @@ import { resolve } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { CUSTOM_PROVIDERS_STORAGE_KEY, + CUSTOM_PROVIDER_ICON, + CUSTOM_PROVIDER_ICON_DARK, } from '../modules/custom-providers.js'; -import { setCustomProviderDescriptors } from '../modules/provider-registry.js'; +import { + resetExtraProviderDescriptors, + setCustomProviderDescriptors, +} from '../modules/provider-registry.js'; import { SNAPSHOT_MESSAGES, captureCurrentView, @@ -186,6 +191,7 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp } document.body.innerHTML = ''; setCustomProviderDescriptors([]); + resetExtraProviderDescriptors(); vi.restoreAllMocks(); delete globalThis.fetch; delete globalThis.createImageBitmap; @@ -546,7 +552,7 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp expect(customIframe.getAttribute('src')).toBe('http://127.0.0.1:3000/chat'); }); - it('sends text-only INJECT_TEXT_WITH_IMAGES (images: []) to imageUpload: false panels, shows localized toast, and never puts them in failedFillPanelIds because of images', async () => { + it('forwards images to custom web panels by default, and gracefully treats runtime reason: "unsupported" as image-skipped without blocking fill cleanup', async () => { const { mpMod, chatgptEl, deepseekEl, customEl } = await bootMultiPanelWithBuiltinsAndCustom(); @@ -554,6 +560,267 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp const deepseekIframe = deepseekEl.querySelector('iframe'); const customIframe = customEl.querySelector('iframe'); + const attachActionResponder = ( + iframe, + { providerId, origin, failReason = null } + ) => { + const calls = []; + const cw = { + postMessage: vi.fn((message, targetOrigin) => { + calls.push({ message: structuredClone(message), targetOrigin }); + if (targetOrigin !== origin) { + return; + } + if (message.type === 'INJECT_TEXT_WITH_IMAGES' && message.action === 'fill') { + queueMicrotask(() => { + const ev = new MessageEvent('message', { + origin, + source: cw, + data: failReason + ? { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: message.requestId, + provider: providerId, + action: 'fill', + status: 'failed', + reason: failReason, + succeededImageIds: [], + } + : { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: message.requestId, + provider: providerId, + action: 'fill', + status: 'succeeded', + succeededImageIds: (message.images || []).map((img) => img.id), + }, + }); + window.dispatchEvent(ev); + }); + } + }), + }; + Object.defineProperty(iframe, 'contentWindow', { + configurable: true, + value: cw, + }); + return { cw, calls }; + }; + + const chatgptFrame = attachActionResponder(chatgptIframe, { + providerId: 'chatgpt', + origin: 'https://chatgpt.com', + }); + const deepseekFrame = attachActionResponder(deepseekIframe, { + providerId: 'deepseek', + origin: 'https://chat.deepseek.com', + }); + const customFrame = attachActionResponder(customIframe, { + providerId: CUSTOM_RECORD.id, + origin: 'http://127.0.0.1:3000', + }); + + const pngBytes = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]); + const imageFile = new File([pngBytes], 'diagram.png', { type: 'image/png' }); + const fileInput = document.getElementById('image-file-input'); + Object.defineProperty(fileInput, 'files', { + configurable: true, + value: [imageFile], + }); + fileInput.dispatchEvent(new Event('change')); + + await vi.waitFor(() => { + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(1); + }); + + document.querySelectorAll('.panelize-toast').forEach((el) => el.remove()); + + // 1. Image-capable custom web panel (e.g. Perplexity) receives full images payload and succeeds with zero skipped toast + await mpMod.broadcastMessage('Explain this architecture diagram', false); + + expect(chatgptFrame.calls[0].message.images).toHaveLength(1); + expect(deepseekFrame.calls[0].message.images).toHaveLength(1); + expect(customFrame.calls).toHaveLength(1); + expect(customFrame.calls[0].targetOrigin).toBe('http://127.0.0.1:3000'); + expect(customFrame.calls[0].message.type).toBe('INJECT_TEXT_WITH_IMAGES'); + expect(customFrame.calls[0].message.providerId).toBe(CUSTOM_RECORD.id); + expect(customFrame.calls[0].message.images).toHaveLength(1); + expect(customFrame.calls[0].message.images[0].name).toBe('diagram.png'); + + const fillBtn = document.getElementById('fill-input-btn'); + expect(fillBtn.dataset.retryFailed).toBe('false'); + expect(document.getElementById('send-status').textContent).toBe('Filled 3 inputs'); + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(0); + expect( + Array.from(document.querySelectorAll('.panelize-toast')).map((el) => el.textContent) + ).not.toContain('Images were not sent to: Local Open WebUI'); + + // 2. Text-only custom web site replying reason: 'unsupported' triggers localized skipped toast without entering failedFillPanelIds + const textOnlyCustomFrame = attachActionResponder(customIframe, { + providerId: CUSTOM_RECORD.id, + origin: 'http://127.0.0.1:3000', + failReason: 'unsupported', + }); + chatgptFrame.calls.length = 0; + deepseekFrame.calls.length = 0; + + const secondFile = new File([pngBytes], 'second.png', { type: 'image/png' }); + Object.defineProperty(fileInput, 'files', { + configurable: true, + value: [secondFile], + }); + fileInput.dispatchEvent(new Event('change')); + await vi.waitFor(() => { + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(1); + }); + document.querySelectorAll('.panelize-toast').forEach((el) => el.remove()); + + await mpMod.broadcastMessage('Text fallback prompt', false); + + expect(textOnlyCustomFrame.calls[0].message.images).toHaveLength(1); + expect(fillBtn.dataset.retryFailed).toBe('false'); + expect(document.getElementById('send-status').textContent).toBe('Filled 3 inputs'); + expect(document.querySelectorAll('.image-preview-item')).toHaveLength(0); + expect( + Array.from(document.querySelectorAll('.panelize-toast')).map((el) => el.textContent) + ).toContain('Images were not sent to: Local Open WebUI'); + }); + + it('sends ENABLE_TEMP_CHAT on custom web iframe load when temporary chat is enabled and DISABLE_TEMP_CHAT when disabled', async () => { + const { customEl } = await bootMultiPanelWithBuiltinsAndCustom(); + const customIframe = customEl.querySelector('iframe'); + const sentTypes = []; + + const cw = { + postMessage: vi.fn((message, targetOrigin) => { + if (targetOrigin !== 'http://127.0.0.1:3000') return; + sentTypes.push(message.type); + if (message.type === 'PANELIZE_CUSTOM_FRAME_PING') { + queueMicrotask(() => { + window.dispatchEvent( + new MessageEvent('message', { + origin: 'http://127.0.0.1:3000', + source: cw, + data: { + type: 'PANELIZE_CUSTOM_FRAME_PONG', + provider: CUSTOM_RECORD.id, + requestId: message.requestId, + context: 'multi-panel-provider-status', + }, + }) + ); + }); + } else if (message.type === 'ENABLE_TEMP_CHAT') { + queueMicrotask(() => { + window.dispatchEvent( + new MessageEvent('message', { + origin: 'http://127.0.0.1:3000', + source: cw, + data: { + type: 'PANELIZE_TEMP_CHAT_ENABLED', + provider: CUSTOM_RECORD.id, + context: 'multi-panel-provider-status', + }, + }) + ); + }); + } else if (message.type === 'DISABLE_TEMP_CHAT') { + queueMicrotask(() => { + window.dispatchEvent( + new MessageEvent('message', { + origin: 'http://127.0.0.1:3000', + source: cw, + data: { + type: 'PANELIZE_TEMP_CHAT_DISABLED', + provider: CUSTOM_RECORD.id, + context: 'multi-panel-provider-status', + }, + }) + ); + }); + } + }), + }; + Object.defineProperty(customIframe, 'contentWindow', { + configurable: true, + value: cw, + }); + + const tempBtn = document.getElementById('temporary-chat-btn'); + tempBtn.click(); + expect(customIframe.getAttribute('src')).toBe('http://127.0.0.1:3000/chat'); + + // Simulate iframe load after reload -> triggers ping -> ENABLE_TEMP_CHAT + customIframe.dispatchEvent(new Event('load')); + await vi.waitFor(() => { + expect(sentTypes).toContain('ENABLE_TEMP_CHAT'); + }); + + // Now disable temporary chat -> reloads iframe -> on load sends DISABLE_TEMP_CHAT + sentTypes.length = 0; + tempBtn.disabled = false; + tempBtn.click(); + customIframe.dispatchEvent(new Event('load')); + await vi.waitFor(() => { + expect(sentTypes).toContain('DISABLE_TEMP_CHAT'); + }); + }); + + it('sends text-only INJECT_TEXT_WITH_IMAGES (images: []) to explicit imageUpload: false descriptors, shows localized toast, and never puts them in failedFillPanelIds because of images', async () => { + vi.resetModules(); + document.body.innerHTML = MULTI_PANEL_BODY_HTML; + + installStatefulChromeStorage({ + localInitial: {}, + syncInitial: { + theme: 'light', + language: 'en', + multiPanelLayout: '1x3', + enabledProviders: ['chatgpt', 'deepseek', 'textonly-builtin'], + providerOrder: ['chatgpt', 'deepseek', 'textonly-builtin'], + multiPanelProviders: ['chatgpt', 'deepseek', 'textonly-builtin'], + }, + }); + + const regMod = await import('../modules/provider-registry.js'); + regMod.registerExtraProviderDescriptors([ + { + id: 'textonly-builtin', + name: 'TextOnly AI', + url: 'http://127.0.0.1:3000/chat', + topLevelUrl: 'http://127.0.0.1:3000/chat', + icon: CUSTOM_PROVIDER_ICON, + iconDark: CUSTOM_PROVIDER_ICON_DARK, + enabled: true, + access: 'builtin', + frameOrigins: ['http://127.0.0.1:3000'], + allowedHosts: ['127.0.0.1'], + permissionOrigins: null, + contentScript: null, + frameRule: null, + tempChat: null, + capabilities: { + imageUpload: false, + inPageNewChat: false, + snapshotStitch: false, + }, + }, + ]); + + const mpMod = await import('../multi-panel/multi-panel.js'); + await vi.waitFor(() => { + expect(document.querySelectorAll('#panel-grid .panel-item')).toHaveLength(3); + }); + const [chatgptEl, deepseekEl, customEl] = Array.from( + document.querySelectorAll('#panel-grid .panel-item') + ); + + const chatgptIframe = chatgptEl.querySelector('iframe'); + const deepseekIframe = deepseekEl.querySelector('iframe'); + const customIframe = customEl.querySelector('iframe'); + const attachActionResponder = (iframe, { providerId, origin, failUpload = false }) => { const calls = []; const cw = { @@ -610,7 +877,7 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp origin: 'https://chat.deepseek.com', }); const customFrame = attachActionResponder(customIframe, { - providerId: CUSTOM_RECORD.id, + providerId: 'textonly-builtin', origin: 'http://127.0.0.1:3000', }); @@ -644,14 +911,13 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp expect(deepseekFrame.calls[0].message.images).toHaveLength(1); expect('providerId' in deepseekFrame.calls[0].message).toBe(false); - // Custom panel received INJECT_TEXT_WITH_IMAGES with images: [], action: 'fill', and providerId + // imageUpload: false panel received INJECT_TEXT_WITH_IMAGES with images: [] expect(customFrame.calls).toHaveLength(1); expect(customFrame.calls[0]).toEqual({ targetOrigin: 'http://127.0.0.1:3000', message: expect.objectContaining({ type: 'INJECT_TEXT_WITH_IMAGES', context: 'multi-panel', - providerId: CUSTOM_RECORD.id, action: 'fill', text: 'Explain this architecture diagram', images: [], @@ -659,16 +925,16 @@ describe('B2.3 provider capability gates (inPageNewChat, snapshotStitch, imageUp }), }); - // Waiter succeeded for all panels; custom panel did NOT enter failedFillPanelIds + // Waiter succeeded for all panels; imageUpload: false panel did NOT enter failedFillPanelIds const fillBtn = document.getElementById('fill-input-btn'); expect(fillBtn.dataset.retryFailed).toBe('false'); expect(document.getElementById('send-status').textContent).toBe('Filled 3 inputs'); - // One localized toast naming the skipped custom panel was displayed + // One localized toast naming the skipped panel was displayed const toasts = Array.from(document.querySelectorAll('.panelize-toast')).map( (el) => el.textContent ); - expect(toasts).toContain('Images were not sent to: Local Open WebUI'); + expect(toasts).toContain('Images were not sent to: TextOnly AI'); // Now verify partial failure + image-only empty-text broadcast: // Make DeepSeek fail image upload while ChatGPT succeeds and Custom skips images with empty text diff --git a/tests/custom-provider-driver.test.js b/tests/custom-provider-driver.test.js index 75984a3..7da97bd 100644 --- a/tests/custom-provider-driver.test.js +++ b/tests/custom-provider-driver.test.js @@ -1031,4 +1031,453 @@ describe('content-scripts/custom-provider-driver.js', () => { } } }); + + it('toggles Perplexity-style sticky incognito button on ENABLE_TEMP_CHAT and exits on DISABLE_TEMP_CHAT without double-toggling when already active', async () => { + const env = createDriverEnvironment({ + url: 'https://www.perplexity.ai/', + ancestorOrigins: [EXTENSION_ORIGIN], + }); + + try { + let isIncognito = false; + let hydrated = false; + let clickCount = 0; + + env.document.body.innerHTML = ` +
+ Incognito privacy policy + +
+
+
+
+ `; + + const incognitoBtn = setLayoutRect(env.document.getElementById('incognito-btn'), { + left: 440, + top: 12, + width: 32, + height: 32, + }); + setLayoutRect(env.document.getElementById('privacy-link'), { + left: 300, + top: 12, + width: 120, + height: 24, + }); + setLayoutRect(env.document.getElementById('ask-input')); + + const privacyClickSpy = vi.fn((e) => e.preventDefault()); + env.document.getElementById('privacy-link').addEventListener('click', privacyClickSpy); + + const syncUi = () => { + env.document.cookie = `pplx.is-incognito=${isIncognito ? 'true' : 'false'}; path=/`; + incognitoBtn.setAttribute( + 'aria-label', + isIncognito + ? 'Exit incognito' + : "Use incognito: create anonymous sessions that aren't saved to your history and expire after 24 hours" + ); + }; + syncUi(); + + incognitoBtn.addEventListener('click', () => { + clickCount += 1; + if (!hydrated) { + return; + } + isIncognito = !isIncognito; + syncUi(); + }); + + env.evaluateDriver(); + env.parent.postMessage.mockClear(); + + // 1. Pre-hydration click does not flip state -> driver must NOT falsely report enabled yet + env.postFromHost({ + type: 'ENABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(260); + expect(clickCount).toBe(1); + expect(isIncognito).toBe(false); + expect( + env.parent.postMessage.mock.calls.some(([msg]) => msg.type === 'PANELIZE_TEMP_CHAT_ENABLED') + ).toBe(false); + + // 2. Hydrated retry activates incognito and reports PANELIZE_TEMP_CHAT_ENABLED + hydrated = true; + env.postFromHost({ + type: 'ENABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(120); + expect(clickCount).toBe(2); + expect(isIncognito).toBe(true); + expect(privacyClickSpy).not.toHaveBeenCalled(); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_ENABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + + // 3. Subsequent ENABLE_TEMP_CHAT while already active is idempotent (must NOT click Exit incognito) + env.parent.postMessage.mockClear(); + env.postFromHost({ + type: 'ENABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(80); + expect(clickCount).toBe(2); + expect(isIncognito).toBe(true); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_ENABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + + // 4. DISABLE_TEMP_CHAT clicks Exit incognito, clears sticky state, and reports PANELIZE_TEMP_CHAT_DISABLED + env.parent.postMessage.mockClear(); + env.postFromHost({ + type: 'DISABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(120); + expect(clickCount).toBe(3); + expect(isIncognito).toBe(false); + expect(incognitoBtn.getAttribute('aria-label')).toContain('Use incognito'); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_DISABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + + // 5. Duplicate DISABLE_TEMP_CHAT when already off does NOT re-enable incognito + env.parent.postMessage.mockClear(); + env.postFromHost({ + type: 'DISABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(80); + expect(clickCount).toBe(3); + expect(isIncognito).toBe(false); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_DISABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + } finally { + await env.close(); + } + }); + + it('toggles generic aria-pressed / role="switch" temporary chat controls on ENABLE_TEMP_CHAT and DISABLE_TEMP_CHAT', async () => { + const env = createDriverEnvironment({ + url: 'http://127.0.0.1:3000/', + ancestorOrigins: [EXTENSION_ORIGIN], + }); + + try { + env.document.body.innerHTML = ` + + + `; + const tempSwitch = setLayoutRect(env.document.getElementById('temp-switch'), { + left: 600, + top: 16, + width: 88, + height: 30, + }); + setLayoutRect(env.document.getElementById('composer')); + + tempSwitch.addEventListener('click', () => { + const next = tempSwitch.getAttribute('aria-checked') !== 'true'; + tempSwitch.setAttribute('aria-checked', next ? 'true' : 'false'); + }); + + env.evaluateDriver(); + env.parent.postMessage.mockClear(); + + env.postFromHost({ + type: 'ENABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(100); + expect(tempSwitch.getAttribute('aria-checked')).toBe('true'); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_ENABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + + env.parent.postMessage.mockClear(); + env.postFromHost({ + type: 'DISABLE_TEMP_CHAT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + }); + await wait(100); + expect(tempSwitch.getAttribute('aria-checked')).toBe('false'); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_TEMP_CHAT_DISABLED', + provider: CUSTOM_PROVIDER_ID, + context: 'multi-panel-provider-status', + }, + EXTENSION_ORIGIN + ); + } finally { + await env.close(); + } + }); + + it('uploads multiple images via Perplexity-style , waits for .png -> .jpg transcoding and disabled preview completion, injects text, and clears attachments on CLEAR_INPUT', async () => { + const env = createDriverEnvironment({ + url: 'https://www.perplexity.ai/', + ancestorOrigins: [EXTENSION_ORIGIN], + }); + + try { + env.document.body.innerHTML = ` +
+
+
+ +
+ + +
+ `; + + setLayoutRect(env.document.getElementById('composer-shell'), { + left: 20, + top: 420, + width: 720, + height: 140, + }); + const strip = setLayoutRect(env.document.getElementById('attachment-strip'), { + left: 24, + top: 424, + width: 680, + height: 56, + }); + const composer = setLayoutRect(env.document.getElementById('composer')); + const fileInput = env.document.getElementById('file-input'); + setLayoutRect(env.document.getElementById('submit-btn'), { + left: 680, + top: 500, + width: 40, + height: 36, + }); + + let receivedFiles = []; + fileInput.addEventListener('change', () => { + receivedFiles = Array.from(fileInput.files || []); + for (const file of receivedFiles) { + const stem = file.name.replace(/\.[^.]+$/, ''); + const chip = env.document.createElement('div'); + chip.className = 'upload-chip'; + + const previewBtn = env.document.createElement('button'); + previewBtn.type = 'button'; + previewBtn.disabled = true; + previewBtn.setAttribute('aria-label', `Preview ${file.name}`); + + const removeBtn = env.document.createElement('button'); + removeBtn.type = 'button'; + removeBtn.setAttribute('aria-label', `Remove ${file.name}`); + setLayoutRect(removeBtn, { left: 60, top: 428, width: 20, height: 20 }); + removeBtn.addEventListener('click', () => { + chip.remove(); + }); + + chip.append(previewBtn, removeBtn); + strip.appendChild(chip); + + // Simulate Perplexity's async .png -> .jpg transcode while still disabled, then blob finish + setTimeout(() => { + previewBtn.setAttribute('aria-label', `Preview ${stem}.jpg`); + removeBtn.setAttribute('aria-label', `Remove ${stem}.jpg`); + }, 60); + + setTimeout(() => { + const thumb = env.document.createElement('img'); + thumb.setAttribute('src', `blob:https://www.perplexity.ai/${stem}`); + thumb.setAttribute('alt', `${stem}.jpg`); + previewBtn.appendChild(thumb); + previewBtn.disabled = false; + }, 180); + } + }); + + env.evaluateDriver(); + env.parent.postMessage.mockClear(); + + const pngDataUrl = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; + + env.postFromHost({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + requestId: 'req-pplx-multi-img', + action: 'fill', + text: 'Compare these two charts', + images: [ + { id: 'img-a', name: 'chart-alpha.png', type: 'image/png', dataUrl: pngDataUrl }, + { id: 'img-b', name: 'chart-beta.png', type: 'image/png', dataUrl: pngDataUrl }, + ], + autoSubmit: false, + }); + + // Must NOT resolve early at 90ms while previewBtn.disabled is still true + await wait(90); + expect( + env.parent.postMessage.mock.calls.some(([msg]) => msg.type === 'PANELIZE_ACTION_RESULT') + ).toBe(false); + + await wait(260); + expect(receivedFiles.map((f) => f.name)).toEqual(['chart-alpha.png', 'chart-beta.png']); + expect(composer.value).toBe('Compare these two charts'); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'req-pplx-multi-img', + provider: CUSTOM_PROVIDER_ID, + action: 'fill', + status: 'succeeded', + succeededImageIds: ['img-a', 'img-b'], + }, + EXTENSION_ORIGIN + ); + + // CLEAR_INPUT with clearImages: true removes both uploaded chips and clears composer text + env.postFromHost({ + type: 'CLEAR_INPUT', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + clearImages: true, + }); + + await wait(40); + expect(composer.value).toBe(''); + expect(strip.querySelectorAll('.upload-chip')).toHaveLength(0); + } finally { + await env.close(); + } + }); + + it('falls back to ClipboardEvent("paste") for image-only fill when no exists in DOM', async () => { + const env = createDriverEnvironment({ + url: 'http://127.0.0.1:3000/chat', + ancestorOrigins: [EXTENSION_ORIGIN], + }); + + try { + env.document.body.innerHTML = ` +
+
+
+ +
+ `; + setLayoutRect(env.document.getElementById('chat-form'), { + left: 20, + top: 440, + width: 680, + height: 120, + }); + const previews = env.document.getElementById('previews'); + const editor = setLayoutRect(env.document.getElementById('editor')); + setLayoutRect(env.document.getElementById('send'), { + left: 620, + top: 500, + width: 60, + height: 36, + }); + + let pastedFileNames = []; + editor.addEventListener('paste', (ev) => { + const files = Array.from(ev.clipboardData?.files || []); + if (files.length > 0) { + ev.preventDefault(); + pastedFileNames = files.map((f) => f.name); + setTimeout(() => { + for (const file of files) { + const img = env.document.createElement('img'); + img.setAttribute('src', `blob:http://127.0.0.1:3000/${file.name}`); + img.setAttribute('alt', file.name); + previews.appendChild(img); + } + }, 50); + } + }); + + env.evaluateDriver(); + env.parent.postMessage.mockClear(); + + const pngDataUrl = + 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=='; + + env.postFromHost({ + type: 'INJECT_TEXT_WITH_IMAGES', + context: 'multi-panel', + providerId: CUSTOM_PROVIDER_ID, + requestId: 'req-paste-image-only', + action: 'fill', + text: '', + images: [{ id: 'img-paste-1', name: 'pasted.png', type: 'image/png', dataUrl: pngDataUrl }], + autoSubmit: false, + }); + + await wait(180); + expect(pastedFileNames).toEqual(['pasted.png']); + expect(env.parent.postMessage).toHaveBeenCalledWith( + { + type: 'PANELIZE_ACTION_RESULT', + context: 'multi-panel-action-result', + requestId: 'req-paste-image-only', + provider: CUSTOM_PROVIDER_ID, + action: 'fill', + status: 'succeeded', + succeededImageIds: ['img-paste-1'], + }, + EXTENSION_ORIGIN + ); + } finally { + await env.close(); + } + }); }); diff --git a/tests/custom-providers-registry-and-storage.test.js b/tests/custom-providers-registry-and-storage.test.js index bcc4d05..b5ee164 100644 --- a/tests/custom-providers-registry-and-storage.test.js +++ b/tests/custom-providers-registry-and-storage.test.js @@ -175,9 +175,13 @@ describe('custom providers: registry, id rules, URL validation, and storage hydr id: 10000, urlFilter: '|http://localhost:3000/', }, - tempChat: null, + tempChat: { + url: null, + normalUrl: 'http://localhost:3000/chat?model=llama', + retry: true, + }, capabilities: { - imageUpload: false, + imageUpload: true, inPageNewChat: false, snapshotStitch: false, }, @@ -188,6 +192,7 @@ describe('custom providers: registry, id rules, URL validation, and storage hydr expect(Object.isFrozen(descriptor.permissionOrigins)).toBe(true); expect(Object.isFrozen(descriptor.contentScript)).toBe(true); expect(Object.isFrozen(descriptor.frameRule)).toBe(true); + expect(Object.isFrozen(descriptor.tempChat)).toBe(true); expect(Object.isFrozen(descriptor.capabilities)).toBe(true); expect(validateProviderDescriptor(descriptor)).toEqual([]); }); @@ -276,13 +281,19 @@ describe('custom providers: registry, id rules, URL validation, and storage hydr }) ).not.toEqual([]); - // Non-null tempChat on custom + // Invalid tempChat on custom (retry: false without URL, or cross-origin normalUrl) expect( validateProviderDescriptor({ ...base, tempChat: { url: null, normalUrl: 'http://localhost:3000/', retry: false }, }) ).not.toEqual([]); + expect( + validateProviderDescriptor({ + ...base, + tempChat: { url: null, normalUrl: 'https://evil.example/', retry: true }, + }) + ).not.toEqual([]); // Missing capabilities on custom expect( diff --git a/tests/e2e/custom-provider-temp-chat-and-images.e2e.test.js b/tests/e2e/custom-provider-temp-chat-and-images.e2e.test.js new file mode 100644 index 0000000..c379517 --- /dev/null +++ b/tests/e2e/custom-provider-temp-chat-and-images.e2e.test.js @@ -0,0 +1,343 @@ +import { test, expect } from '@playwright/test'; +import { + createPatchedExtensionCopy, + launchExtension, + startFixtureServer, +} from './extension-harness.js'; + +function renderPerplexityLikeFixtureHtml() { + return ` + + + + Perplexity Custom Fixture + + +
+

Perplexity Custom Fixture

+ +
+
+
+
+
+ + + +
+
+ + +`; +} + +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); +} + +test.describe('Custom web provider Temporary Chat and Image Upload E2E', () => { + test.setTimeout(90_000); + + test('enables/preserves/disables sticky cookie incognito mode and uploads/clears/submits multiple images on a Perplexity-like custom web panel', async () => { + // Minimal 1x1 PNG buffer + const pngBuffer = Buffer.from( + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==', + 'base64' + ); + + 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(renderPerplexityLikeFixtureHtml()); + }); + + 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 }, + }); + await waitForServiceWorkerReady(extension); + + await extension.serviceWorker.evaluate(async () => { + await chrome.storage.sync.set({ + enabledProviders: [], + providerOrder: [], + multiPanelProviders: [], + multiPanelLayout: '1x1', + }); + }); + + 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 extension.serviceWorker.evaluate(async (id) => { + await chrome.storage.sync.set({ + enabledProviders: [id], + providerOrder: [id], + multiPanelProviders: [id], + multiPanelLayout: '1x1', + }); + }, customId); + + const mpPage = await extension.context.newPage(); + await mpPage.goto(extension.extensionUrl('multi-panel/multi-panel.html')); + + const iframeLocator = mpPage.locator( + '#panel-grid .panel-item[data-custom-provider="true"] iframe' + ); + await expect(iframeLocator).toBeVisible(); + + const readIncognitoState = async () => { + const handle = await iframeLocator.elementHandle(); + const frame = await handle?.contentFrame(); + if (!frame) return null; + return frame + .evaluate(() => document.getElementById('incognito-toggle')?.dataset.incognito ?? null) + .catch(() => null); + }; + + await expect.poll(readIncognitoState, { timeout: 15_000 }).toBe('false'); + + // 1. Enable Temporary Chat -> reloads custom panel and activates Incognito + await mpPage.locator('#temporary-chat-btn').click(); + await expect(mpPage.locator('#temporary-chat-btn')).toHaveAttribute('aria-pressed', 'true'); + await expect.poll(readIncognitoState, { timeout: 15_000 }).toBe('true'); + + // 2. Click New Chat while Temporary Chat is ON -> preserves Incognito without toggling it off + await expect(mpPage.locator('#new-chat-btn')).toBeEnabled({ timeout: 5_000 }); + await mpPage.locator('#new-chat-btn').click(); + await expect.poll(readIncognitoState, { timeout: 15_000 }).toBe('true'); + + // 3. Disable Temporary Chat -> reloads custom panel and exits sticky cookie Incognito + await expect(mpPage.locator('#temporary-chat-btn')).toBeEnabled({ timeout: 5_000 }); + await mpPage.locator('#temporary-chat-btn').click(); + await expect(mpPage.locator('#temporary-chat-btn')).toHaveAttribute('aria-pressed', 'false'); + await expect.poll(readIncognitoState, { timeout: 15_000 }).toBe('false'); + + // 4. Upload 1 image + text -> Fill -> Clear All removes in-panel attachment chip & text + await mpPage.locator('#image-file-input').setInputFiles([ + { name: 'draft-shot.png', mimeType: 'image/png', buffer: pngBuffer }, + ]); + await mpPage.locator('#unified-input').fill('Draft prompt to clear'); + await mpPage.locator('#fill-input-btn').click(); + await expect(mpPage.locator('#image-preview-container .image-preview-item')).toHaveCount(0, { + timeout: 15_000, + }); + + const customFrame = mpPage + .locator('#panel-grid .panel-item[data-custom-provider="true"]') + .frameLocator('iframe'); + await expect(customFrame.locator('.attachment-chip')).toHaveCount(1); + await expect(customFrame.locator('#composer')).toHaveValue('Draft prompt to clear'); + + await mpPage.locator('#clear-all-btn').click(); + await expect(customFrame.locator('.attachment-chip')).toHaveCount(0); + await expect(customFrame.locator('#composer')).toHaveValue(''); + + // 5. Upload 2 PNG images + prompt text -> Send All (fills & clears unified bar) -> Send All (submits) + await mpPage.locator('#image-file-input').setInputFiles([ + { name: 'first-shot.png', mimeType: 'image/png', buffer: pngBuffer }, + { name: 'second-shot.png', mimeType: 'image/png', buffer: pngBuffer }, + ]); + await expect(mpPage.locator('#image-preview-container .image-preview-item')).toHaveCount(2); + + await mpPage.locator('#unified-input').fill('Analyze both screenshots'); + await mpPage.locator('#send-all-btn').click(); + + // Wait for fill completion: unified input & image previews clear automatically + await expect(mpPage.locator('#image-preview-container .image-preview-item')).toHaveCount(0, { + timeout: 15_000, + }); + await expect(mpPage.locator('#unified-input')).toHaveValue(''); + + // Second Send All triggers submit inside the custom panel + await expect(mpPage.locator('#send-all-btn')).toBeEnabled(); + await mpPage.locator('#send-all-btn').click(); + + await expect + .poll( + async () => { + const handle = await iframeLocator.elementHandle(); + const frame = await handle?.contentFrame(); + if (!frame) return null; + return frame + .evaluate(() => { + const turn = document.querySelector('.submitted-turn'); + return turn + ? { + text: turn.textContent, + attachments: turn.dataset.attachments, + incognito: turn.dataset.incognito, + } + : null; + }) + .catch(() => null); + }, + { timeout: 15_000 } + ) + .toEqual({ + text: 'Analyze both screenshots', + attachments: 'first-shot,second-shot', + incognito: 'false', + }); + } finally { + await extension?.close(); + await extensionCopy.cleanup(); + await fixture.close(); + } + }); +}); diff --git a/tests/panel-message-contract.test.js b/tests/panel-message-contract.test.js index c810acc..694fe69 100644 --- a/tests/panel-message-contract.test.js +++ b/tests/panel-message-contract.test.js @@ -200,17 +200,18 @@ describe('panel-message-contract', () => { expect(contractSource).toContain('iframe.contentWindow'); }); - it('forward check: every listed host-to-frame message appears in a host sender and in the content-script receiver', () => { - const receiverSource = readProjectSource('content-scripts/text-injection-all-providers.js'); - + it('forward check: every listed host-to-frame message appears in a host sender and in a listed content-script receiver', () => { for (const entry of HOST_TO_FRAME_MESSAGES) { expect(entry.direction).toBe('host-to-frame'); const appearsInListedSender = entry.senderFiles.some((senderFile) => containsQuotedLiteral(readProjectSource(senderFile), entry.type) ); expect(appearsInListedSender, `host sender missing ${entry.type}`).toBe(true); + const appearsInListedReceiver = entry.receiverFiles.some((receiverFile) => + containsQuotedLiteral(readProjectSource(receiverFile), entry.type) + ); expect( - containsQuotedLiteral(receiverSource, entry.type), + appearsInListedReceiver, `content-script receiver missing ${entry.type}` ).toBe(true); @@ -223,13 +224,14 @@ describe('panel-message-contract', () => { } }); - it('forward check: every listed frame-to-host message appears in the content-script sender and in its host receiver', () => { - const senderSource = readProjectSource('content-scripts/text-injection-all-providers.js'); - + it('forward check: every listed frame-to-host message appears in a listed content-script sender and in its host receiver', () => { for (const entry of FRAME_TO_HOST_MESSAGES) { expect(entry.direction).toBe('frame-to-host'); + const appearsInListedSender = entry.senderFiles.some((senderFile) => + containsQuotedLiteral(readProjectSource(senderFile), entry.type) + ); expect( - containsQuotedLiteral(senderSource, entry.type), + appearsInListedSender, `content-script sender missing ${entry.type}` ).toBe(true); @@ -239,8 +241,11 @@ describe('panel-message-contract', () => { expect(appearsInListedReceiver, `host receiver missing ${entry.type}`).toBe(true); if (entry.action) { + const actionInSender = entry.senderFiles.some((senderFile) => + containsQuotedLiteral(readProjectSource(senderFile), entry.action) + ); expect( - containsQuotedLiteral(senderSource, entry.action), + actionInSender, `content-script sender missing action ${entry.action}` ).toBe(true); const actionInReceiver = entry.receiverFiles.some((receiverFile) =>