feat(chrome-qwen-bridge): 🔥 init chrome qwen code bridge

This commit is contained in:
yiliang114
2025-12-20 00:58:41 +08:00
parent a92be72e88
commit a60c5c6697
57 changed files with 9489 additions and 0 deletions

View File

@@ -0,0 +1,366 @@
/**
* Background Service Worker for Qwen CLI Bridge
* Handles communication between extension components and native host
*/
// Native messaging host name
const NATIVE_HOST_NAME = 'com.qwen.cli.bridge';
// Connection state
let nativePort = null;
let isConnected = false;
let qwenCliStatus = 'disconnected';
let pendingRequests = new Map();
let requestId = 0;
// Connection management
function connectToNativeHost() {
if (nativePort) {
return Promise.resolve(nativePort);
}
return new Promise((resolve, reject) => {
try {
console.log('Attempting to connect to Native Host:', NATIVE_HOST_NAME);
nativePort = chrome.runtime.connectNative(NATIVE_HOST_NAME);
// Check for immediate errors
if (chrome.runtime.lastError) {
console.error('Chrome runtime error:', chrome.runtime.lastError);
reject(new Error(chrome.runtime.lastError.message));
return;
}
nativePort.onMessage.addListener((message) => {
console.log('Native message received:', message);
handleNativeMessage(message);
});
nativePort.onDisconnect.addListener(() => {
const error = chrome.runtime.lastError;
console.log('Native host disconnected');
if (error) {
console.error('Disconnect error:', error);
}
nativePort = null;
isConnected = false;
qwenCliStatus = 'disconnected';
// Reject all pending requests
for (const [id, handler] of pendingRequests) {
handler.reject(new Error('Native host disconnected'));
}
pendingRequests.clear();
// Notify popup of disconnection
chrome.runtime.sendMessage({
type: 'STATUS_UPDATE',
status: 'disconnected'
}).catch(() => {}); // Ignore errors if popup is closed
});
// Send initial handshake
console.log('Sending handshake...');
nativePort.postMessage({ type: 'handshake', version: '1.0.0' });
// Set timeout for handshake response
const handshakeTimeout = setTimeout(() => {
console.error('Handshake timeout - no response from Native Host');
if (nativePort) {
nativePort.disconnect();
}
reject(new Error('Handshake timeout'));
}, 5000);
// Store timeout so we can clear it when we get response
nativePort._handshakeTimeout = handshakeTimeout;
isConnected = true;
qwenCliStatus = 'connected';
resolve(nativePort);
} catch (error) {
console.error('Failed to connect to native host:', error);
reject(error);
}
});
}
// Handle messages from native host
function handleNativeMessage(message) {
if (message.type === 'handshake_response') {
console.log('Handshake successful:', message);
// Clear handshake timeout
if (nativePort && nativePort._handshakeTimeout) {
clearTimeout(nativePort._handshakeTimeout);
delete nativePort._handshakeTimeout;
}
qwenCliStatus = message.qwenStatus || 'connected';
// Notify popup of connection
chrome.runtime.sendMessage({
type: 'STATUS_UPDATE',
status: qwenCliStatus,
capabilities: message.capabilities
}).catch(() => {});
} else if (message.type === 'response' && message.id !== undefined) {
// Handle response to a specific request
const handler = pendingRequests.get(message.id);
if (handler) {
if (message.error) {
handler.reject(new Error(message.error));
} else {
handler.resolve(message.data);
}
pendingRequests.delete(message.id);
}
} else if (message.type === 'event') {
// Handle events from Qwen CLI
handleQwenEvent(message);
}
}
// Send request to native host
async function sendToNativeHost(message) {
if (!nativePort || !isConnected) {
await connectToNativeHost();
}
return new Promise((resolve, reject) => {
const id = ++requestId;
pendingRequests.set(id, { resolve, reject });
nativePort.postMessage({
...message,
id
});
// Set timeout for request
setTimeout(() => {
if (pendingRequests.has(id)) {
pendingRequests.delete(id);
reject(new Error('Request timeout'));
}
}, 30000); // 30 second timeout
});
}
// Handle events from Qwen CLI
function handleQwenEvent(event) {
console.log('Qwen event:', event);
// Forward event to content scripts and popup
chrome.tabs.query({}, (tabs) => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(tab.id, {
type: 'QWEN_EVENT',
event: event.data
}).catch(() => {}); // Ignore errors for tabs without content script
});
});
chrome.runtime.sendMessage({
type: 'QWEN_EVENT',
event: event.data
}).catch(() => {});
}
// Message handlers from extension components
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('Message received:', request, 'from:', sender);
if (request.type === 'CONNECT') {
// Connect to native host
connectToNativeHost()
.then(() => {
sendResponse({ success: true, status: qwenCliStatus });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true; // Will respond asynchronously
}
if (request.type === 'GET_STATUS') {
// Get current connection status
sendResponse({
connected: isConnected,
status: qwenCliStatus
});
return false;
}
if (request.type === 'EXTRACT_PAGE_DATA') {
// Request page data from content script
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
if (tabs[0]) {
chrome.tabs.sendMessage(tabs[0].id, {
type: 'EXTRACT_DATA'
}, (response) => {
if (chrome.runtime.lastError) {
sendResponse({
success: false,
error: chrome.runtime.lastError.message
});
} else {
sendResponse(response);
}
});
} else {
sendResponse({
success: false,
error: 'No active tab found'
});
}
});
return true; // Will respond asynchronously
}
if (request.type === 'SEND_TO_QWEN') {
// Send data to Qwen CLI via native host
sendToNativeHost({
type: 'qwen_request',
action: request.action,
data: request.data
})
.then(response => {
sendResponse({ success: true, data: response });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true; // Will respond asynchronously
}
if (request.type === 'START_QWEN_CLI') {
// Request native host to start Qwen CLI
sendToNativeHost({
type: 'start_qwen',
config: request.config || {}
})
.then(response => {
qwenCliStatus = 'running';
sendResponse({ success: true, data: response });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true; // Will respond asynchronously
}
if (request.type === 'STOP_QWEN_CLI') {
// Request native host to stop Qwen CLI
sendToNativeHost({
type: 'stop_qwen'
})
.then(response => {
qwenCliStatus = 'stopped';
sendResponse({ success: true, data: response });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true; // Will respond asynchronously
}
if (request.type === 'CAPTURE_SCREENSHOT') {
// Capture screenshot of active tab
chrome.tabs.captureVisibleTab(null, { format: 'png' }, (dataUrl) => {
if (chrome.runtime.lastError) {
sendResponse({
success: false,
error: chrome.runtime.lastError.message
});
} else {
sendResponse({
success: true,
data: dataUrl
});
}
});
return true; // Will respond asynchronously
}
if (request.type === 'GET_NETWORK_LOGS') {
// Get network logs (requires debugger API)
getNetworkLogs(sender.tab?.id)
.then(logs => {
sendResponse({ success: true, data: logs });
})
.catch(error => {
sendResponse({ success: false, error: error.message });
});
return true; // Will respond asynchronously
}
});
// Network logging using debugger API
const debuggerTargets = new Map();
async function getNetworkLogs(tabId) {
if (!tabId) {
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
tabId = tabs[0]?.id;
if (!tabId) throw new Error('No active tab found');
}
// Check if debugger is already attached
if (!debuggerTargets.has(tabId)) {
await chrome.debugger.attach({ tabId }, '1.3');
await chrome.debugger.sendCommand({ tabId }, 'Network.enable');
// Store network logs
debuggerTargets.set(tabId, { logs: [] });
// Listen for network events
chrome.debugger.onEvent.addListener((source, method, params) => {
if (source.tabId === tabId) {
const target = debuggerTargets.get(tabId);
if (target && method.startsWith('Network.')) {
target.logs.push({
method,
params,
timestamp: Date.now()
});
}
}
});
}
const target = debuggerTargets.get(tabId);
return target?.logs || [];
}
// Clean up debugger on tab close
chrome.tabs.onRemoved.addListener((tabId) => {
if (debuggerTargets.has(tabId)) {
chrome.debugger.detach({ tabId });
debuggerTargets.delete(tabId);
}
});
// Listen for extension installation or update
chrome.runtime.onInstalled.addListener((details) => {
console.log('Extension installed/updated:', details);
if (details.reason === 'install') {
// Just log the installation, don't auto-open options
console.log('Extension installed for the first time');
// Users can access options from popup menu
}
});
// Open side panel when extension icon is clicked
chrome.action.onClicked.addListener((tab) => {
chrome.sidePanel.open({ windowId: tab.windowId });
});
// Export for testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
connectToNativeHost,
sendToNativeHost
};
}

View File

@@ -0,0 +1,466 @@
/**
* Content Script for Qwen CLI Bridge
* Extracts data from web pages and communicates with background script
*/
// Data extraction functions
function extractPageData() {
const data = {
// Basic page info
url: window.location.href,
title: document.title,
domain: window.location.hostname,
path: window.location.pathname,
timestamp: new Date().toISOString(),
// Meta information
meta: {},
// Page content
content: {
text: '',
html: '',
markdown: ''
},
// Structured data
links: [],
images: [],
forms: [],
// Console logs
consoleLogs: [],
// Performance metrics
performance: {}
};
// Extract meta tags
document.querySelectorAll('meta').forEach(meta => {
const name = meta.getAttribute('name') || meta.getAttribute('property');
const content = meta.getAttribute('content');
if (name && content) {
data.meta[name] = content;
}
});
// Extract main content (try to find article or main element first)
const mainContent = document.querySelector('article, main, [role="main"]') || document.body;
data.content.text = extractTextContent(mainContent);
data.content.html = mainContent.innerHTML;
data.content.markdown = htmlToMarkdown(mainContent);
// Extract all links
document.querySelectorAll('a[href]').forEach(link => {
data.links.push({
text: link.textContent.trim(),
href: link.href,
target: link.target,
isExternal: isExternalLink(link.href)
});
});
// Extract all images
document.querySelectorAll('img').forEach(img => {
data.images.push({
src: img.src,
alt: img.alt,
title: img.title,
width: img.naturalWidth,
height: img.naturalHeight
});
});
// Extract form data (structure only, no sensitive data)
document.querySelectorAll('form').forEach(form => {
const formData = {
action: form.action,
method: form.method,
fields: []
};
form.querySelectorAll('input, textarea, select').forEach(field => {
formData.fields.push({
type: field.type || field.tagName.toLowerCase(),
name: field.name,
id: field.id,
placeholder: field.placeholder,
required: field.required
});
});
data.forms.push(formData);
});
// Get performance metrics
if (window.performance && window.performance.timing) {
const perf = window.performance.timing;
data.performance = {
loadTime: perf.loadEventEnd - perf.navigationStart,
domReady: perf.domContentLoadedEventEnd - perf.navigationStart,
firstPaint: getFirstPaintTime()
};
}
return data;
}
// Extract clean text content
function extractTextContent(element) {
// Clone the element to avoid modifying the original
const clone = element.cloneNode(true);
// Remove script and style elements
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
// Get text content and clean it up
let text = clone.textContent || '';
// Remove excessive whitespace
text = text.replace(/\s+/g, ' ').trim();
// Limit length to prevent excessive data
const maxLength = 50000; // 50KB limit
if (text.length > maxLength) {
text = text.substring(0, maxLength) + '...';
}
return text;
}
// Simple HTML to Markdown converter
function htmlToMarkdown(element) {
const clone = element.cloneNode(true);
// Remove script and style elements
clone.querySelectorAll('script, style, noscript').forEach(el => el.remove());
let markdown = '';
const walker = document.createTreeWalker(
clone,
NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT,
null,
false
);
let node;
let listStack = [];
while (node = walker.nextNode()) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent.trim();
if (text) {
markdown += text + ' ';
}
} else if (node.nodeType === Node.ELEMENT_NODE) {
switch (node.tagName.toLowerCase()) {
case 'h1':
markdown += '\n# ' + node.textContent.trim() + '\n';
break;
case 'h2':
markdown += '\n## ' + node.textContent.trim() + '\n';
break;
case 'h3':
markdown += '\n### ' + node.textContent.trim() + '\n';
break;
case 'h4':
markdown += '\n#### ' + node.textContent.trim() + '\n';
break;
case 'h5':
markdown += '\n##### ' + node.textContent.trim() + '\n';
break;
case 'h6':
markdown += '\n###### ' + node.textContent.trim() + '\n';
break;
case 'p':
markdown += '\n' + node.textContent.trim() + '\n';
break;
case 'br':
markdown += '\n';
break;
case 'a':
const href = node.getAttribute('href');
const text = node.textContent.trim();
if (href) {
markdown += `[${text}](${href}) `;
}
break;
case 'img':
const src = node.getAttribute('src');
const alt = node.getAttribute('alt') || '';
if (src) {
markdown += `![${alt}](${src}) `;
}
break;
case 'ul':
case 'ol':
markdown += '\n';
listStack.push(node.tagName.toLowerCase());
break;
case 'li':
const listType = listStack[listStack.length - 1];
const prefix = listType === 'ol' ? '1. ' : '- ';
markdown += prefix + node.textContent.trim() + '\n';
break;
case 'code':
markdown += '`' + node.textContent + '`';
break;
case 'pre':
markdown += '\n```\n' + node.textContent + '\n```\n';
break;
case 'blockquote':
markdown += '\n> ' + node.textContent.trim() + '\n';
break;
case 'strong':
case 'b':
markdown += '**' + node.textContent + '**';
break;
case 'em':
case 'i':
markdown += '*' + node.textContent + '*';
break;
}
}
}
// Limit markdown length
const maxLength = 30000;
if (markdown.length > maxLength) {
markdown = markdown.substring(0, maxLength) + '...';
}
return markdown.trim();
}
// Check if link is external
function isExternalLink(url) {
try {
const link = new URL(url);
return link.hostname !== window.location.hostname;
} catch {
return false;
}
}
// Get first paint time
function getFirstPaintTime() {
if (window.performance && window.performance.getEntriesByType) {
const paintEntries = window.performance.getEntriesByType('paint');
const firstPaint = paintEntries.find(entry => entry.name === 'first-paint');
return firstPaint ? firstPaint.startTime : null;
}
return null;
}
// Console log interceptor
const consoleLogs = [];
const originalConsole = {
log: console.log,
error: console.error,
warn: console.warn,
info: console.info
};
// Intercept console methods
['log', 'error', 'warn', 'info'].forEach(method => {
console[method] = function(...args) {
// Store the log
consoleLogs.push({
type: method,
message: args.map(arg => {
try {
if (typeof arg === 'object') {
return JSON.stringify(arg);
}
return String(arg);
} catch {
return String(arg);
}
}).join(' '),
timestamp: new Date().toISOString(),
stack: new Error().stack
});
// Keep only last 100 logs to prevent memory issues
if (consoleLogs.length > 100) {
consoleLogs.shift();
}
// Call original console method
originalConsole[method].apply(console, args);
};
});
// Get selected text
function getSelectedText() {
return window.getSelection().toString();
}
// Highlight element on page
function highlightElement(selector) {
try {
const element = document.querySelector(selector);
if (element) {
// Store original style
const originalStyle = element.style.cssText;
// Apply highlight
element.style.cssText += `
outline: 3px solid #FF6B6B !important;
background-color: rgba(255, 107, 107, 0.1) !important;
transition: all 0.3s ease !important;
`;
// Remove highlight after 3 seconds
setTimeout(() => {
element.style.cssText = originalStyle;
}, 3000);
return true;
}
return false;
} catch (error) {
console.error('Failed to highlight element:', error);
return false;
}
}
// Execute custom JavaScript in page context
function executeInPageContext(code) {
try {
const script = document.createElement('script');
script.textContent = `
(function() {
try {
const result = ${code};
window.postMessage({
type: 'QWEN_BRIDGE_RESULT',
success: true,
result: result
}, '*');
} catch (error) {
window.postMessage({
type: 'QWEN_BRIDGE_RESULT',
success: false,
error: error.message
}, '*');
}
})();
`;
document.documentElement.appendChild(script);
script.remove();
return new Promise((resolve, reject) => {
const listener = (event) => {
if (event.data && event.data.type === 'QWEN_BRIDGE_RESULT') {
window.removeEventListener('message', listener);
if (event.data.success) {
resolve(event.data.result);
} else {
reject(new Error(event.data.error));
}
}
};
window.addEventListener('message', listener);
// Timeout after 5 seconds
setTimeout(() => {
window.removeEventListener('message', listener);
reject(new Error('Execution timeout'));
}, 5000);
});
} catch (error) {
return Promise.reject(error);
}
}
// Message listener for communication with background script
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
console.log('Content script received message:', request);
switch (request.type) {
case 'EXTRACT_DATA':
// Extract and send page data
const pageData = extractPageData();
pageData.consoleLogs = consoleLogs;
sendResponse({
success: true,
data: pageData
});
break;
case 'GET_SELECTED_TEXT':
// Get currently selected text
sendResponse({
success: true,
data: getSelectedText()
});
break;
case 'HIGHLIGHT_ELEMENT':
// Highlight an element on the page
const highlighted = highlightElement(request.selector);
sendResponse({
success: highlighted
});
break;
case 'EXECUTE_CODE':
// Execute JavaScript in page context
executeInPageContext(request.code)
.then(result => {
sendResponse({
success: true,
data: result
});
})
.catch(error => {
sendResponse({
success: false,
error: error.message
});
});
return true; // Will respond asynchronously
case 'SCROLL_TO':
// Scroll to specific position
window.scrollTo({
top: request.y || 0,
left: request.x || 0,
behavior: request.smooth ? 'smooth' : 'auto'
});
sendResponse({ success: true });
break;
case 'QWEN_EVENT':
// Handle events from Qwen CLI
console.log('Qwen event received:', request.event);
// Could trigger UI updates or other actions based on event
break;
default:
sendResponse({
success: false,
error: 'Unknown request type'
});
}
});
// Notify background script that content script is loaded
chrome.runtime.sendMessage({
type: 'CONTENT_SCRIPT_LOADED',
url: window.location.href
}).catch(() => {
// Ignore errors if background script is not ready
});
// Export for testing
if (typeof module !== 'undefined' && module.exports) {
module.exports = {
extractPageData,
extractTextContent,
htmlToMarkdown,
getSelectedText,
highlightElement
};
}

View File

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="20" fill="url(#grad)"/>
<path d="M32 64 L64 32 L64 48 L96 48 L64 80 L64 64 Z" fill="white" stroke="white" stroke-width="2" stroke-linejoin="round"/>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
<stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 530 B

View File

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="20" fill="url(#grad)"/>
<path d="M32 64 L64 32 L64 48 L96 48 L64 80 L64 64 Z" fill="white" stroke="white" stroke-width="2" stroke-linejoin="round"/>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
<stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 530 B

View File

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="20" fill="url(#grad)"/>
<path d="M32 64 L64 32 L64 48 L96 48 L64 80 L64 64 Z" fill="white" stroke="white" stroke-width="2" stroke-linejoin="round"/>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
<stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 530 B

View File

@@ -0,0 +1,10 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 128 128" width="128" height="128">
<rect width="128" height="128" rx="20" fill="url(#grad)"/>
<path d="M32 64 L64 32 L64 48 L96 48 L64 80 L64 64 Z" fill="white" stroke="white" stroke-width="2" stroke-linejoin="round"/>
<defs>
<linearGradient id="grad" x1="0%" y1="0%" x2="100%" y2="100%">
<stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
<stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
</linearGradient>
</defs>
</svg>

After

Width:  |  Height:  |  Size: 530 B

View File

@@ -0,0 +1,58 @@
{
"manifest_version": 3,
"name": "Qwen CLI Bridge",
"version": "1.0.0",
"description": "Bridge between Chrome browser and Qwen CLI for enhanced AI interactions",
"permissions": [
"activeTab",
"tabs",
"storage",
"nativeMessaging",
"debugger",
"webNavigation",
"scripting",
"cookies",
"webRequest",
"sidePanel"
],
"host_permissions": [
"<all_urls>"
],
"background": {
"service_worker": "background/service-worker.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content/content-script.js"],
"run_at": "document_idle"
}
],
"action": {
"default_icon": {
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
}
},
"side_panel": {
"default_path": "sidepanel/sidepanel.html"
},
"options_ui": {
"page": "options/options.html",
"open_in_tab": true
},
"icons": {
"16": "icons/icon-16.png",
"48": "icons/icon-48.png",
"128": "icons/icon-128.png"
}
}

View File

@@ -0,0 +1,217 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qwen CLI Bridge - Options</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
padding: 40px 20px;
}
.container {
max-width: 800px;
margin: 0 auto;
background: white;
border-radius: 20px;
box-shadow: 0 20px 60px rgba(0,0,0,0.2);
padding: 40px;
}
h1 {
color: #333;
font-size: 2em;
margin-bottom: 10px;
}
.subtitle {
color: #666;
margin-bottom: 30px;
}
.section {
margin: 30px 0;
padding: 25px;
background: #f8f9fa;
border-radius: 10px;
}
.section h2 {
color: #667eea;
margin-bottom: 15px;
font-size: 1.3em;
}
.option-group {
margin: 20px 0;
}
label {
display: block;
margin-bottom: 8px;
color: #444;
font-weight: 500;
}
input[type="text"],
input[type="number"],
textarea {
width: 100%;
padding: 10px 15px;
border: 2px solid #e0e0e0;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s;
}
input:focus,
textarea:focus {
outline: none;
border-color: #667eea;
}
input[type="checkbox"] {
margin-right: 8px;
}
.checkbox-label {
display: flex;
align-items: center;
cursor: pointer;
}
button {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 12px 24px;
border-radius: 8px;
font-size: 16px;
cursor: pointer;
transition: transform 0.2s;
}
button:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.save-status {
display: inline-block;
margin-left: 15px;
color: #4caf50;
opacity: 0;
transition: opacity 0.3s;
}
.save-status.show {
opacity: 1;
}
.help-text {
font-size: 12px;
color: #999;
margin-top: 5px;
}
.info-box {
background: #e3f2fd;
border-left: 4px solid #2196f3;
padding: 15px;
margin: 20px 0;
border-radius: 4px;
}
.info-box h3 {
color: #1976d2;
margin-bottom: 8px;
}
.info-box p {
color: #555;
}
</style>
</head>
<body>
<div class="container">
<h1>⚙️ Qwen CLI Bridge Settings</h1>
<p class="subtitle">Configure your Chrome extension and Qwen CLI integration</p>
<div class="section">
<h2>🔌 Connection Settings</h2>
<div class="option-group">
<label for="httpPort">HTTP Server Port</label>
<input type="number" id="httpPort" min="1024" max="65535" value="8080">
<p class="help-text">Port for Qwen CLI HTTP server (default: 8080)</p>
</div>
<div class="option-group">
<label for="mcpServers">MCP Servers</label>
<input type="text" id="mcpServers" placeholder="chrome-devtools,playwright">
<p class="help-text">Comma-separated list of MCP servers to load</p>
</div>
<div class="option-group">
<label class="checkbox-label">
<input type="checkbox" id="autoConnect">
<span>Auto-connect on startup</span>
</label>
<p class="help-text">Automatically connect to Qwen CLI when opening the popup</p>
</div>
</div>
<div class="section">
<h2>🎨 Display Settings</h2>
<div class="option-group">
<label class="checkbox-label">
<input type="checkbox" id="showNotifications">
<span>Show notifications</span>
</label>
<p class="help-text">Display desktop notifications for important events</p>
</div>
<div class="option-group">
<label class="checkbox-label">
<input type="checkbox" id="debugMode">
<span>Debug mode</span>
</label>
<p class="help-text">Show detailed debug information in console</p>
</div>
</div>
<div class="info-box">
<h3> Native Host Status</h3>
<p id="nativeHostStatus">Checking...</p>
</div>
<div class="info-box">
<h3>📍 Extension ID</h3>
<p id="extensionId">Loading...</p>
</div>
<button id="saveBtn">Save Settings</button>
<span class="save-status" id="saveStatus">✓ Settings saved</span>
<div style="margin-top: 40px; padding-top: 20px; border-top: 1px solid #e0e0e0;">
<p style="text-align: center; color: #999; font-size: 14px;">
Qwen CLI Bridge v1.0.0 |
<a href="https://github.com/QwenLM/qwen-code" style="color: #667eea;">GitHub</a> |
<a href="#" id="helpLink" style="color: #667eea;">Help</a>
</p>
</div>
</div>
<script src="options.js"></script>
</body>
</html>

View File

@@ -0,0 +1,80 @@
/**
* Options page script for Qwen CLI Bridge
*/
// Load saved settings
async function loadSettings() {
const settings = await chrome.storage.local.get([
'httpPort',
'mcpServers',
'autoConnect',
'showNotifications',
'debugMode'
]);
// Set values in form
document.getElementById('httpPort').value = settings.httpPort || 8080;
document.getElementById('mcpServers').value = settings.mcpServers || '';
document.getElementById('autoConnect').checked = settings.autoConnect || false;
document.getElementById('showNotifications').checked = settings.showNotifications || false;
document.getElementById('debugMode').checked = settings.debugMode || false;
}
// Save settings
document.getElementById('saveBtn').addEventListener('click', async () => {
const settings = {
httpPort: parseInt(document.getElementById('httpPort').value) || 8080,
mcpServers: document.getElementById('mcpServers').value,
autoConnect: document.getElementById('autoConnect').checked,
showNotifications: document.getElementById('showNotifications').checked,
debugMode: document.getElementById('debugMode').checked
};
await chrome.storage.local.set(settings);
// Show saved status
const saveStatus = document.getElementById('saveStatus');
saveStatus.classList.add('show');
setTimeout(() => {
saveStatus.classList.remove('show');
}, 2000);
});
// Check Native Host status
async function checkNativeHostStatus() {
try {
// Try to send a message to check if Native Host is installed
chrome.runtime.sendMessage({ type: 'GET_STATUS' }, (response) => {
if (chrome.runtime.lastError) {
document.getElementById('nativeHostStatus').textContent =
'❌ Not installed - Please run install script';
} else if (response && response.connected) {
document.getElementById('nativeHostStatus').textContent =
'✅ Connected and running';
} else {
document.getElementById('nativeHostStatus').textContent =
'⚠️ Installed but not connected';
}
});
} catch (error) {
document.getElementById('nativeHostStatus').textContent =
'❌ Error checking status';
}
}
// Show extension ID
document.getElementById('extensionId').textContent = chrome.runtime.id;
// Help link
document.getElementById('helpLink').addEventListener('click', (e) => {
e.preventDefault();
chrome.tabs.create({
url: 'https://github.com/QwenLM/qwen-code/tree/main/packages/chrome-qwen-bridge'
});
});
// Initialize
document.addEventListener('DOMContentLoaded', () => {
loadSettings();
checkNativeHostStatus();
});

View File

@@ -0,0 +1,385 @@
/* Popup Styles for Qwen CLI Bridge */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
width: 400px;
min-height: 500px;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
color: #333;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
background: white;
min-height: 500px;
display: flex;
flex-direction: column;
}
/* Header */
.header {
padding: 16px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
justify-content: space-between;
align-items: center;
}
.logo {
display: flex;
align-items: center;
gap: 8px;
}
.logo .icon {
width: 24px;
height: 24px;
}
.logo h1 {
font-size: 18px;
font-weight: 600;
}
/* Status Indicator */
.status-indicator {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 12px;
background: rgba(255, 255, 255, 0.2);
border-radius: 12px;
font-size: 12px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ff4444;
animation: pulse 2s infinite;
}
.status-indicator.connected .status-dot {
background: #44ff44;
}
.status-indicator.connecting .status-dot {
background: #ffaa44;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
/* Sections */
.section {
padding: 16px;
border-bottom: 1px solid #e5e5e5;
}
.section:last-of-type {
border-bottom: none;
}
.section h2 {
font-size: 14px;
font-weight: 600;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 12px;
}
/* Buttons */
.btn {
padding: 8px 16px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: #f5f5f5;
color: #333;
}
.btn-secondary:hover:not(:disabled) {
background: #e5e5e5;
}
.btn-small {
padding: 4px 12px;
font-size: 12px;
}
.btn-icon {
width: 32px;
height: 32px;
padding: 4px;
border: none;
background: transparent;
cursor: pointer;
border-radius: 4px;
transition: background 0.2s;
}
.btn-icon:hover {
background: #f5f5f5;
}
.btn-icon svg {
width: 100%;
height: 100%;
stroke: #666;
}
/* Connection Section */
.connection-controls {
display: flex;
gap: 8px;
}
.error-message {
margin-top: 8px;
padding: 8px;
background: #fee;
color: #c00;
border-radius: 4px;
font-size: 12px;
}
/* Action Buttons */
.action-buttons {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.action-btn {
padding: 12px;
border: 1px solid #e5e5e5;
border-radius: 8px;
background: white;
cursor: pointer;
transition: all 0.2s;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
font-size: 12px;
color: #666;
}
.action-btn:hover:not(:disabled) {
border-color: #667eea;
background: #f8f9ff;
color: #667eea;
}
.action-btn:hover:not(:disabled) .action-icon {
stroke: #667eea;
}
.action-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.action-icon {
width: 24px;
height: 24px;
stroke: #999;
}
/* Response Section */
.response-container {
background: #f9f9f9;
border-radius: 8px;
overflow: hidden;
}
.response-header {
padding: 8px 12px;
background: #f0f0f0;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.response-type {
font-size: 12px;
font-weight: 600;
color: #666;
}
.response-content {
padding: 12px;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 12px;
color: #333;
max-height: 200px;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
}
/* Settings Section */
.settings-section details {
cursor: pointer;
}
.settings-section summary {
font-size: 14px;
font-weight: 600;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
padding: 4px 0;
user-select: none;
}
.settings-section summary:hover {
color: #667eea;
}
.settings-content {
margin-top: 12px;
}
.setting-item {
margin-bottom: 12px;
}
.setting-item label {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: #666;
}
.setting-item input[type="text"],
.setting-item input[type="number"] {
width: 100%;
padding: 6px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.setting-item input[type="checkbox"] {
margin-right: 8px;
}
/* Footer */
.footer {
padding: 12px 16px;
background: #f9f9f9;
border-top: 1px solid #e5e5e5;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 12px;
color: #999;
margin-top: auto;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
.version {
color: #bbb;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Loading state */
.loading {
position: relative;
pointer-events: none;
}
.loading::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
}
/* Animations */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.fade-in {
animation: fadeIn 0.3s ease;
}

View File

@@ -0,0 +1,140 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qwen CLI Bridge</title>
<link rel="stylesheet" href="popup.css">
</head>
<body>
<div class="container">
<!-- Header -->
<header class="header">
<div class="logo">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<h1>Qwen CLI Bridge</h1>
</div>
<div class="status-indicator" id="statusIndicator">
<span class="status-dot"></span>
<span class="status-text">Disconnected</span>
</div>
</header>
<!-- Connection Section -->
<section class="section connection-section">
<h2>Connection</h2>
<div class="connection-controls">
<button id="connectBtn" class="btn btn-primary">
Connect to Qwen CLI
</button>
<button id="startQwenBtn" class="btn btn-secondary" disabled>
Start Qwen CLI
</button>
</div>
<div id="connectionError" class="error-message" style="display: none;"></div>
</section>
<!-- Actions Section -->
<section class="section actions-section">
<h2>Quick Actions</h2>
<div class="action-buttons">
<button id="extractDataBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
Extract Page Data
</button>
<button id="captureScreenBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Capture Screenshot
</button>
<button id="analyzePageBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
</svg>
Analyze with AI
</button>
<button id="getSelectedBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Send Selected Text
</button>
<button id="networkLogsBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
</svg>
Network Logs
</button>
<button id="consoleLogsBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
Console Logs
</button>
</div>
</section>
<!-- Response Section -->
<section class="section response-section" id="responseSection" style="display: none;">
<h2>Response</h2>
<div class="response-container">
<div class="response-header">
<span id="responseType" class="response-type"></span>
<button id="copyResponseBtn" class="btn-icon" title="Copy to clipboard">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
</div>
<pre id="responseContent" class="response-content"></pre>
</div>
</section>
<!-- Settings Section -->
<section class="section settings-section">
<details>
<summary>Advanced Settings</summary>
<div class="settings-content">
<div class="setting-item">
<label for="mcpServers">MCP Servers:</label>
<input type="text" id="mcpServers" placeholder="chrome-devtools,playwright" />
</div>
<div class="setting-item">
<label for="httpPort">HTTP Port:</label>
<input type="number" id="httpPort" placeholder="8080" value="8080" />
</div>
<div class="setting-item">
<label for="autoConnect">
<input type="checkbox" id="autoConnect" />
Auto-connect on startup
</label>
</div>
<button id="saveSettingsBtn" class="btn btn-small">Save Settings</button>
</div>
</details>
</section>
<!-- Footer -->
<footer class="footer">
<a href="#" id="openOptionsBtn">Options</a>
<span></span>
<a href="#" id="helpBtn">Help</a>
<span></span>
<span class="version">v1.0.0</span>
</footer>
</div>
<script src="popup.js"></script>
</body>
</html>

View File

@@ -0,0 +1,477 @@
/**
* Popup Script for Qwen CLI Bridge
* Handles UI interactions and communication with background script
*/
// UI Elements
const statusIndicator = document.getElementById('statusIndicator');
const statusText = statusIndicator.querySelector('.status-text');
const connectBtn = document.getElementById('connectBtn');
const startQwenBtn = document.getElementById('startQwenBtn');
const connectionError = document.getElementById('connectionError');
const responseSection = document.getElementById('responseSection');
const responseType = document.getElementById('responseType');
const responseContent = document.getElementById('responseContent');
const copyResponseBtn = document.getElementById('copyResponseBtn');
// Action buttons
const extractDataBtn = document.getElementById('extractDataBtn');
const captureScreenBtn = document.getElementById('captureScreenBtn');
const analyzePageBtn = document.getElementById('analyzePageBtn');
const getSelectedBtn = document.getElementById('getSelectedBtn');
const networkLogsBtn = document.getElementById('networkLogsBtn');
const consoleLogsBtn = document.getElementById('consoleLogsBtn');
// Settings
const mcpServersInput = document.getElementById('mcpServers');
const httpPortInput = document.getElementById('httpPort');
const autoConnectCheckbox = document.getElementById('autoConnect');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
// Footer links
const openOptionsBtn = document.getElementById('openOptionsBtn');
const helpBtn = document.getElementById('helpBtn');
// State
let isConnected = false;
let qwenStatus = 'disconnected';
// Initialize popup
document.addEventListener('DOMContentLoaded', async () => {
await loadSettings();
await checkConnectionStatus();
// Auto-connect if enabled
const settings = await chrome.storage.local.get(['autoConnect']);
if (settings.autoConnect && !isConnected) {
connectToQwen();
}
});
// Load saved settings
async function loadSettings() {
const settings = await chrome.storage.local.get([
'mcpServers',
'httpPort',
'autoConnect'
]);
if (settings.mcpServers) {
mcpServersInput.value = settings.mcpServers;
}
if (settings.httpPort) {
httpPortInput.value = settings.httpPort;
}
if (settings.autoConnect !== undefined) {
autoConnectCheckbox.checked = settings.autoConnect;
}
}
// Save settings
saveSettingsBtn.addEventListener('click', async () => {
await chrome.storage.local.set({
mcpServers: mcpServersInput.value,
httpPort: parseInt(httpPortInput.value) || 8080,
autoConnect: autoConnectCheckbox.checked
});
saveSettingsBtn.textContent = 'Saved!';
setTimeout(() => {
saveSettingsBtn.textContent = 'Save Settings';
}, 2000);
});
// Check connection status
async function checkConnectionStatus() {
try {
const response = await chrome.runtime.sendMessage({ type: 'GET_STATUS' });
updateConnectionStatus(response.connected, response.status);
} catch (error) {
updateConnectionStatus(false, 'disconnected');
}
}
// Update UI based on connection status
function updateConnectionStatus(connected, status) {
isConnected = connected;
qwenStatus = status;
// Update status indicator
statusIndicator.classList.toggle('connected', connected);
statusIndicator.classList.toggle('connecting', status === 'connecting');
statusText.textContent = getStatusText(status);
// Update button states
connectBtn.textContent = connected ? 'Disconnect' : 'Connect to Qwen CLI';
connectBtn.classList.toggle('btn-danger', connected);
startQwenBtn.disabled = !connected || status === 'running';
// Enable/disable action buttons
const actionButtons = [
extractDataBtn,
captureScreenBtn,
analyzePageBtn,
getSelectedBtn,
networkLogsBtn,
consoleLogsBtn
];
actionButtons.forEach(btn => {
btn.disabled = !connected || status !== 'running';
});
}
// Get human-readable status text
function getStatusText(status) {
switch (status) {
case 'connected':
return 'Connected';
case 'running':
return 'Qwen CLI Running';
case 'connecting':
return 'Connecting...';
case 'disconnected':
return 'Disconnected';
case 'stopped':
return 'Qwen CLI Stopped';
default:
return 'Unknown';
}
}
// Connect button handler
connectBtn.addEventListener('click', () => {
if (isConnected) {
disconnectFromQwen();
} else {
connectToQwen();
}
});
// Connect to Qwen CLI
async function connectToQwen() {
updateConnectionStatus(false, 'connecting');
connectionError.style.display = 'none';
try {
const response = await chrome.runtime.sendMessage({ type: 'CONNECT' });
if (response.success) {
updateConnectionStatus(true, response.status);
} else {
throw new Error(response.error || 'Connection failed');
}
} catch (error) {
console.error('Connection error:', error);
connectionError.textContent = `Error: ${error.message}`;
connectionError.style.display = 'block';
updateConnectionStatus(false, 'disconnected');
}
}
// Disconnect from Qwen CLI
function disconnectFromQwen() {
// Simply close the popup to disconnect
// The native port will be closed when the extension unloads
updateConnectionStatus(false, 'disconnected');
window.close();
}
// Start Qwen CLI button handler
startQwenBtn.addEventListener('click', async () => {
startQwenBtn.disabled = true;
startQwenBtn.textContent = 'Starting...';
try {
const settings = await chrome.storage.local.get(['mcpServers', 'httpPort']);
const response = await chrome.runtime.sendMessage({
type: 'START_QWEN_CLI',
config: {
mcpServers: settings.mcpServers ? settings.mcpServers.split(',').map(s => s.trim()) : [],
httpPort: settings.httpPort || 8080
}
});
if (response.success) {
updateConnectionStatus(true, 'running');
showResponse('Qwen CLI Started', response.data || 'Successfully started');
} else {
throw new Error(response.error || 'Failed to start Qwen CLI');
}
} catch (error) {
console.error('Start error:', error);
connectionError.textContent = `Error: ${error.message}`;
connectionError.style.display = 'block';
} finally {
startQwenBtn.textContent = 'Start Qwen CLI';
}
});
// Extract page data button handler
extractDataBtn.addEventListener('click', async () => {
try {
showLoading('Extracting page data...');
const response = await chrome.runtime.sendMessage({
type: 'EXTRACT_PAGE_DATA'
});
if (response.success) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'analyze_page',
data: response.data
});
if (qwenResponse.success) {
showResponse('Page Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to extract data: ${error.message}`);
}
});
// Capture screenshot button handler
captureScreenBtn.addEventListener('click', async () => {
try {
showLoading('Capturing screenshot...');
const response = await chrome.runtime.sendMessage({
type: 'CAPTURE_SCREENSHOT'
});
if (response.success) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'analyze_screenshot',
data: {
screenshot: response.data,
url: (await chrome.tabs.query({ active: true, currentWindow: true }))[0].url
}
});
if (qwenResponse.success) {
showResponse('Screenshot Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to capture screenshot: ${error.message}`);
}
});
// Analyze page with AI button handler
analyzePageBtn.addEventListener('click', async () => {
try {
showLoading('Analyzing page with AI...');
// First extract page data
const extractResponse = await chrome.runtime.sendMessage({
type: 'EXTRACT_PAGE_DATA'
});
if (!extractResponse.success) {
throw new Error(extractResponse.error);
}
// Send to Qwen for AI analysis
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'ai_analyze',
data: {
pageData: extractResponse.data,
prompt: 'Please analyze this webpage and provide insights about its content, purpose, and any notable features.'
}
});
if (qwenResponse.success) {
showResponse('AI Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} catch (error) {
showError(`Analysis failed: ${error.message}`);
}
});
// Get selected text button handler
getSelectedBtn.addEventListener('click', async () => {
try {
showLoading('Getting selected text...');
// Get active tab
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
if (!tab) {
throw new Error('No active tab found');
}
// Get selected text from content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'GET_SELECTED_TEXT'
});
if (response.success && response.data) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'process_text',
data: {
text: response.data,
context: 'selected_text'
}
});
if (qwenResponse.success) {
showResponse('Selected Text Processed', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
showError('No text selected. Please select some text on the page first.');
}
} catch (error) {
showError(`Failed to process selected text: ${error.message}`);
}
});
// Network logs button handler
networkLogsBtn.addEventListener('click', async () => {
try {
showLoading('Getting network logs...');
const response = await chrome.runtime.sendMessage({
type: 'GET_NETWORK_LOGS'
});
if (response.success) {
showResponse('Network Logs', JSON.stringify(response.data, null, 2));
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to get network logs: ${error.message}`);
}
});
// Console logs button handler
consoleLogsBtn.addEventListener('click', async () => {
try {
showLoading('Getting console logs...');
// Get active tab
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
if (!tab) {
throw new Error('No active tab found');
}
// Get console logs from content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'EXTRACT_DATA'
});
if (response.success) {
const consoleLogs = response.data.consoleLogs || [];
if (consoleLogs.length > 0) {
showResponse('Console Logs', JSON.stringify(consoleLogs, null, 2));
} else {
showResponse('Console Logs', 'No console logs captured');
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to get console logs: ${error.message}`);
}
});
// Copy response button handler
copyResponseBtn.addEventListener('click', () => {
const text = responseContent.textContent;
navigator.clipboard.writeText(text).then(() => {
const originalTitle = copyResponseBtn.title;
copyResponseBtn.title = 'Copied!';
setTimeout(() => {
copyResponseBtn.title = originalTitle;
}, 2000);
});
});
// Footer link handlers
openOptionsBtn.addEventListener('click', (e) => {
e.preventDefault();
// Use try-catch to handle potential errors
try {
chrome.runtime.openOptionsPage(() => {
if (chrome.runtime.lastError) {
// If opening options page fails, open it in a new tab as fallback
console.error('Error opening options page:', chrome.runtime.lastError);
chrome.tabs.create({
url: chrome.runtime.getURL('options/options.html')
});
}
});
} catch (error) {
console.error('Failed to open options page:', error);
// Fallback: open in new tab
chrome.tabs.create({
url: chrome.runtime.getURL('options/options.html')
});
}
});
helpBtn.addEventListener('click', (e) => {
e.preventDefault();
chrome.tabs.create({
url: 'https://github.com/QwenLM/qwen-code/tree/main/packages/chrome-qwen-bridge'
});
});
// Helper functions
function showLoading(message) {
responseSection.style.display = 'block';
responseType.textContent = 'Loading';
responseContent.textContent = message;
responseSection.classList.add('loading');
}
function showResponse(type, content) {
responseSection.style.display = 'block';
responseType.textContent = type;
responseContent.textContent = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
responseSection.classList.remove('loading');
responseSection.classList.add('fade-in');
}
function showError(message) {
responseSection.style.display = 'block';
responseType.textContent = 'Error';
responseType.style.color = '#c00';
responseContent.textContent = message;
responseSection.classList.remove('loading');
}
// Listen for status updates from background
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'STATUS_UPDATE') {
updateConnectionStatus(message.status !== 'disconnected', message.status);
} else if (message.type === 'QWEN_EVENT') {
// Handle events from Qwen CLI
console.log('Qwen event received:', message.event);
// Could update UI based on event
}
});

View File

@@ -0,0 +1,402 @@
/* Side Panel Styles for Qwen CLI Bridge */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html, body {
height: 100%;
width: 100%;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
font-size: 14px;
line-height: 1.5;
color: #333;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.container {
background: white;
min-height: 100%;
display: flex;
flex-direction: column;
}
/* Header */
.header {
padding: 16px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
display: flex;
justify-content: space-between;
align-items: center;
position: sticky;
top: 0;
z-index: 100;
}
.logo {
display: flex;
align-items: center;
gap: 8px;
}
.logo .icon {
width: 24px;
height: 24px;
}
.logo h1 {
font-size: 18px;
font-weight: 600;
}
/* Status Indicator */
.status-indicator {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 12px;
background: rgba(255, 255, 255, 0.2);
border-radius: 12px;
font-size: 12px;
}
.status-dot {
width: 8px;
height: 8px;
border-radius: 50%;
background: #ff4444;
animation: pulse 2s infinite;
}
.status-indicator.connected .status-dot {
background: #44ff44;
}
.status-indicator.connecting .status-dot {
background: #ffaa44;
}
@keyframes pulse {
0%, 100% {
opacity: 1;
}
50% {
opacity: 0.5;
}
}
/* Sections */
.section {
padding: 16px;
border-bottom: 1px solid #e5e5e5;
}
.section:last-of-type {
border-bottom: none;
}
.section h2 {
font-size: 14px;
font-weight: 600;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
margin-bottom: 12px;
}
/* Buttons */
.btn {
padding: 8px 16px;
border: none;
border-radius: 6px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.2s;
}
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.btn-primary {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.btn-primary:hover:not(:disabled) {
transform: translateY(-1px);
box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4);
}
.btn-secondary {
background: #f5f5f5;
color: #333;
}
.btn-secondary:hover:not(:disabled) {
background: #e5e5e5;
}
.btn-small {
padding: 4px 12px;
font-size: 12px;
}
.btn-icon {
width: 32px;
height: 32px;
padding: 4px;
border: none;
background: transparent;
cursor: pointer;
border-radius: 4px;
transition: background 0.2s;
}
.btn-icon:hover {
background: #f5f5f5;
}
.btn-icon svg {
width: 100%;
height: 100%;
stroke: #666;
}
/* Connection Section */
.connection-controls {
display: flex;
gap: 8px;
flex-wrap: wrap;
}
.error-message {
margin-top: 8px;
padding: 8px;
background: #fee;
color: #c00;
border-radius: 4px;
font-size: 12px;
}
/* Action Buttons */
.action-buttons {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 8px;
}
.action-btn {
padding: 12px;
border: 1px solid #e5e5e5;
border-radius: 8px;
background: white;
cursor: pointer;
transition: all 0.2s;
display: flex;
flex-direction: column;
align-items: center;
gap: 8px;
font-size: 12px;
color: #666;
}
.action-btn:hover:not(:disabled) {
border-color: #667eea;
background: #f8f9ff;
color: #667eea;
}
.action-btn:hover:not(:disabled) .action-icon {
stroke: #667eea;
}
.action-btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.action-icon {
width: 24px;
height: 24px;
stroke: #999;
}
/* Response Section */
.response-section {
flex: 1;
display: flex;
flex-direction: column;
}
.response-container {
background: #f9f9f9;
border-radius: 8px;
overflow: hidden;
flex: 1;
display: flex;
flex-direction: column;
}
.response-header {
padding: 8px 12px;
background: #f0f0f0;
border-bottom: 1px solid #e0e0e0;
display: flex;
justify-content: space-between;
align-items: center;
}
.response-type {
font-size: 12px;
font-weight: 600;
color: #666;
}
.response-content {
padding: 12px;
font-family: 'Consolas', 'Monaco', 'Courier New', monospace;
font-size: 12px;
color: #333;
flex: 1;
overflow-y: auto;
white-space: pre-wrap;
word-break: break-all;
max-height: 400px;
}
/* Settings Section */
.settings-section details {
cursor: pointer;
}
.settings-section summary {
font-size: 14px;
font-weight: 600;
color: #666;
text-transform: uppercase;
letter-spacing: 0.5px;
padding: 4px 0;
user-select: none;
}
.settings-section summary:hover {
color: #667eea;
}
.settings-content {
margin-top: 12px;
}
.setting-item {
margin-bottom: 12px;
}
.setting-item label {
display: block;
margin-bottom: 4px;
font-size: 12px;
color: #666;
}
.setting-item input[type="text"],
.setting-item input[type="number"] {
width: 100%;
padding: 6px 8px;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 14px;
}
.setting-item input[type="checkbox"] {
margin-right: 8px;
}
/* Footer */
.footer {
padding: 12px 16px;
background: #f9f9f9;
border-top: 1px solid #e5e5e5;
display: flex;
align-items: center;
justify-content: center;
gap: 8px;
font-size: 12px;
color: #999;
margin-top: auto;
}
.footer a {
color: #667eea;
text-decoration: none;
}
.footer a:hover {
text-decoration: underline;
}
.version {
color: #bbb;
}
/* Scrollbar */
::-webkit-scrollbar {
width: 6px;
height: 6px;
}
::-webkit-scrollbar-track {
background: #f1f1f1;
}
::-webkit-scrollbar-thumb {
background: #888;
border-radius: 3px;
}
::-webkit-scrollbar-thumb:hover {
background: #555;
}
/* Loading state */
.loading {
position: relative;
pointer-events: none;
}
.loading::after {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(255, 255, 255, 0.8);
display: flex;
align-items: center;
justify-content: center;
}
/* Animations */
@keyframes fadeIn {
from {
opacity: 0;
transform: translateY(10px);
}
to {
opacity: 1;
transform: translateY(0);
}
}
.fade-in {
animation: fadeIn 0.3s ease;
}

View File

@@ -0,0 +1,140 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Qwen CLI Bridge</title>
<link rel="stylesheet" href="sidepanel.css">
</head>
<body>
<div class="container">
<!-- Header -->
<header class="header">
<div class="logo">
<svg class="icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z" />
</svg>
<h1>Qwen CLI Bridge</h1>
</div>
<div class="status-indicator" id="statusIndicator">
<span class="status-dot"></span>
<span class="status-text">Disconnected</span>
</div>
</header>
<!-- Connection Section -->
<section class="section connection-section">
<h2>Connection</h2>
<div class="connection-controls">
<button id="connectBtn" class="btn btn-primary">
Connect to Qwen CLI
</button>
<button id="startQwenBtn" class="btn btn-secondary" disabled>
Start Qwen CLI
</button>
</div>
<div id="connectionError" class="error-message" style="display: none;"></div>
</section>
<!-- Actions Section -->
<section class="section actions-section">
<h2>Quick Actions</h2>
<div class="action-buttons">
<button id="extractDataBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
</svg>
Extract Page Data
</button>
<button id="captureScreenBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z" />
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
</svg>
Capture Screenshot
</button>
<button id="analyzePageBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
</svg>
Analyze with AI
</button>
<button id="getSelectedBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
Send Selected Text
</button>
<button id="networkLogsBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
</svg>
Network Logs
</button>
<button id="consoleLogsBtn" class="action-btn" disabled>
<svg class="action-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 9l3 3-3 3m5 0h3M5 20h14a2 2 0 002-2V6a2 2 0 00-2-2H5a2 2 0 00-2 2v12a2 2 0 002 2z" />
</svg>
Console Logs
</button>
</div>
</section>
<!-- Response Section -->
<section class="section response-section" id="responseSection" style="display: none;">
<h2>Response</h2>
<div class="response-container">
<div class="response-header">
<span id="responseType" class="response-type"></span>
<button id="copyResponseBtn" class="btn-icon" title="Copy to clipboard">
<svg viewBox="0 0 24 24" fill="none" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z" />
</svg>
</button>
</div>
<pre id="responseContent" class="response-content"></pre>
</div>
</section>
<!-- Settings Section -->
<section class="section settings-section">
<details>
<summary>Advanced Settings</summary>
<div class="settings-content">
<div class="setting-item">
<label for="mcpServers">MCP Servers:</label>
<input type="text" id="mcpServers" placeholder="chrome-devtools,playwright" />
</div>
<div class="setting-item">
<label for="httpPort">HTTP Port:</label>
<input type="number" id="httpPort" placeholder="8080" value="8080" />
</div>
<div class="setting-item">
<label for="autoConnect">
<input type="checkbox" id="autoConnect" />
Auto-connect on startup
</label>
</div>
<button id="saveSettingsBtn" class="btn btn-small">Save Settings</button>
</div>
</details>
</section>
<!-- Footer -->
<footer class="footer">
<a href="#" id="openOptionsBtn">Options</a>
<span></span>
<a href="#" id="helpBtn">Help</a>
<span></span>
<span class="version">v1.0.0</span>
</footer>
</div>
<script src="sidepanel.js"></script>
</body>
</html>

View File

@@ -0,0 +1,480 @@
/**
* Side Panel Script for Qwen CLI Bridge
* Handles UI interactions and communication with background script
*/
// UI Elements
const statusIndicator = document.getElementById('statusIndicator');
const statusText = statusIndicator.querySelector('.status-text');
const connectBtn = document.getElementById('connectBtn');
const startQwenBtn = document.getElementById('startQwenBtn');
const connectionError = document.getElementById('connectionError');
const responseSection = document.getElementById('responseSection');
const responseType = document.getElementById('responseType');
const responseContent = document.getElementById('responseContent');
const copyResponseBtn = document.getElementById('copyResponseBtn');
// Action buttons
const extractDataBtn = document.getElementById('extractDataBtn');
const captureScreenBtn = document.getElementById('captureScreenBtn');
const analyzePageBtn = document.getElementById('analyzePageBtn');
const getSelectedBtn = document.getElementById('getSelectedBtn');
const networkLogsBtn = document.getElementById('networkLogsBtn');
const consoleLogsBtn = document.getElementById('consoleLogsBtn');
// Settings
const mcpServersInput = document.getElementById('mcpServers');
const httpPortInput = document.getElementById('httpPort');
const autoConnectCheckbox = document.getElementById('autoConnect');
const saveSettingsBtn = document.getElementById('saveSettingsBtn');
// Footer links
const openOptionsBtn = document.getElementById('openOptionsBtn');
const helpBtn = document.getElementById('helpBtn');
// State
let isConnected = false;
let qwenStatus = 'disconnected';
// Initialize side panel
document.addEventListener('DOMContentLoaded', async () => {
await loadSettings();
await checkConnectionStatus();
// Auto-connect if enabled
const settings = await chrome.storage.local.get(['autoConnect']);
if (settings.autoConnect && !isConnected) {
connectToQwen();
}
});
// Load saved settings
async function loadSettings() {
const settings = await chrome.storage.local.get([
'mcpServers',
'httpPort',
'autoConnect'
]);
if (settings.mcpServers) {
mcpServersInput.value = settings.mcpServers;
}
if (settings.httpPort) {
httpPortInput.value = settings.httpPort;
}
if (settings.autoConnect !== undefined) {
autoConnectCheckbox.checked = settings.autoConnect;
}
}
// Save settings
saveSettingsBtn.addEventListener('click', async () => {
await chrome.storage.local.set({
mcpServers: mcpServersInput.value,
httpPort: parseInt(httpPortInput.value) || 8080,
autoConnect: autoConnectCheckbox.checked
});
saveSettingsBtn.textContent = 'Saved!';
setTimeout(() => {
saveSettingsBtn.textContent = 'Save Settings';
}, 2000);
});
// Check connection status
async function checkConnectionStatus() {
try {
const response = await chrome.runtime.sendMessage({ type: 'GET_STATUS' });
updateConnectionStatus(response.connected, response.status);
} catch (error) {
updateConnectionStatus(false, 'disconnected');
}
}
// Update UI based on connection status
function updateConnectionStatus(connected, status) {
isConnected = connected;
qwenStatus = status;
// Update status indicator
statusIndicator.classList.toggle('connected', connected);
statusIndicator.classList.toggle('connecting', status === 'connecting');
statusText.textContent = getStatusText(status);
// Update button states
connectBtn.textContent = connected ? 'Disconnect' : 'Connect to Qwen CLI';
connectBtn.classList.toggle('btn-danger', connected);
startQwenBtn.disabled = !connected || status === 'running';
// Enable/disable action buttons
const actionButtons = [
extractDataBtn,
captureScreenBtn,
analyzePageBtn,
getSelectedBtn,
networkLogsBtn,
consoleLogsBtn
];
actionButtons.forEach(btn => {
btn.disabled = !connected || status !== 'running';
});
}
// Get human-readable status text
function getStatusText(status) {
switch (status) {
case 'connected':
return 'Connected';
case 'running':
return 'Qwen CLI Running';
case 'connecting':
return 'Connecting...';
case 'disconnected':
return 'Disconnected';
case 'stopped':
return 'Qwen CLI Stopped';
default:
return 'Unknown';
}
}
// Connect button handler
connectBtn.addEventListener('click', () => {
if (isConnected) {
disconnectFromQwen();
} else {
connectToQwen();
}
});
// Connect to Qwen CLI
async function connectToQwen() {
updateConnectionStatus(false, 'connecting');
connectionError.style.display = 'none';
try {
const response = await chrome.runtime.sendMessage({ type: 'CONNECT' });
if (response.success) {
updateConnectionStatus(true, response.status);
} else {
throw new Error(response.error || 'Connection failed');
}
} catch (error) {
console.error('Connection error:', error);
connectionError.textContent = `Error: ${error.message}`;
connectionError.style.display = 'block';
updateConnectionStatus(false, 'disconnected');
}
}
// Disconnect from Qwen CLI
async function disconnectFromQwen() {
try {
await chrome.runtime.sendMessage({ type: 'DISCONNECT' });
} catch (error) {
console.error('Disconnect error:', error);
}
updateConnectionStatus(false, 'disconnected');
}
// Start Qwen CLI button handler
startQwenBtn.addEventListener('click', async () => {
startQwenBtn.disabled = true;
startQwenBtn.textContent = 'Starting...';
try {
const settings = await chrome.storage.local.get(['mcpServers', 'httpPort']);
const response = await chrome.runtime.sendMessage({
type: 'START_QWEN_CLI',
config: {
mcpServers: settings.mcpServers ? settings.mcpServers.split(',').map(s => s.trim()) : [],
httpPort: settings.httpPort || 8080
}
});
if (response.success) {
updateConnectionStatus(true, 'running');
showResponse('Qwen CLI Started', response.data || 'Successfully started');
} else {
throw new Error(response.error || 'Failed to start Qwen CLI');
}
} catch (error) {
console.error('Start error:', error);
connectionError.textContent = `Error: ${error.message}`;
connectionError.style.display = 'block';
} finally {
startQwenBtn.textContent = 'Start Qwen CLI';
}
});
// Extract page data button handler
extractDataBtn.addEventListener('click', async () => {
try {
showLoading('Extracting page data...');
const response = await chrome.runtime.sendMessage({
type: 'EXTRACT_PAGE_DATA'
});
if (response.success) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'analyze_page',
data: response.data
});
if (qwenResponse.success) {
showResponse('Page Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to extract data: ${error.message}`);
}
});
// Capture screenshot button handler
captureScreenBtn.addEventListener('click', async () => {
try {
showLoading('Capturing screenshot...');
const response = await chrome.runtime.sendMessage({
type: 'CAPTURE_SCREENSHOT'
});
if (response.success) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'analyze_screenshot',
data: {
screenshot: response.data,
url: (await chrome.tabs.query({ active: true, currentWindow: true }))[0].url
}
});
if (qwenResponse.success) {
showResponse('Screenshot Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to capture screenshot: ${error.message}`);
}
});
// Analyze page with AI button handler
analyzePageBtn.addEventListener('click', async () => {
try {
showLoading('Analyzing page with AI...');
// First extract page data
const extractResponse = await chrome.runtime.sendMessage({
type: 'EXTRACT_PAGE_DATA'
});
if (!extractResponse.success) {
throw new Error(extractResponse.error);
}
// Send to Qwen for AI analysis
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'ai_analyze',
data: {
pageData: extractResponse.data,
prompt: 'Please analyze this webpage and provide insights about its content, purpose, and any notable features.'
}
});
if (qwenResponse.success) {
showResponse('AI Analysis', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} catch (error) {
showError(`Analysis failed: ${error.message}`);
}
});
// Get selected text button handler
getSelectedBtn.addEventListener('click', async () => {
try {
showLoading('Getting selected text...');
// Get active tab
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
if (!tab) {
throw new Error('No active tab found');
}
// Get selected text from content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'GET_SELECTED_TEXT'
});
if (response.success && response.data) {
// Send to Qwen CLI
const qwenResponse = await chrome.runtime.sendMessage({
type: 'SEND_TO_QWEN',
action: 'process_text',
data: {
text: response.data,
context: 'selected_text'
}
});
if (qwenResponse.success) {
showResponse('Selected Text Processed', qwenResponse.data);
} else {
throw new Error(qwenResponse.error);
}
} else {
showError('No text selected. Please select some text on the page first.');
}
} catch (error) {
showError(`Failed to process selected text: ${error.message}`);
}
});
// Network logs button handler
networkLogsBtn.addEventListener('click', async () => {
try {
showLoading('Getting network logs...');
const response = await chrome.runtime.sendMessage({
type: 'GET_NETWORK_LOGS'
});
if (response.success) {
showResponse('Network Logs', JSON.stringify(response.data, null, 2));
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to get network logs: ${error.message}`);
}
});
// Console logs button handler
consoleLogsBtn.addEventListener('click', async () => {
try {
showLoading('Getting console logs...');
// Get active tab
const tabs = await chrome.tabs.query({ active: true, currentWindow: true });
const tab = tabs[0];
if (!tab) {
throw new Error('No active tab found');
}
// Get console logs from content script
const response = await chrome.tabs.sendMessage(tab.id, {
type: 'EXTRACT_DATA'
});
if (response.success) {
const consoleLogs = response.data.consoleLogs || [];
if (consoleLogs.length > 0) {
showResponse('Console Logs', JSON.stringify(consoleLogs, null, 2));
} else {
showResponse('Console Logs', 'No console logs captured');
}
} else {
throw new Error(response.error);
}
} catch (error) {
showError(`Failed to get console logs: ${error.message}`);
}
});
// Copy response button handler
copyResponseBtn.addEventListener('click', () => {
const text = responseContent.textContent;
navigator.clipboard.writeText(text).then(() => {
const originalTitle = copyResponseBtn.title;
copyResponseBtn.title = 'Copied!';
setTimeout(() => {
copyResponseBtn.title = originalTitle;
}, 2000);
});
});
// Footer link handlers
openOptionsBtn.addEventListener('click', (e) => {
e.preventDefault();
// Use try-catch to handle potential errors
try {
chrome.runtime.openOptionsPage(() => {
if (chrome.runtime.lastError) {
// If opening options page fails, open it in a new tab as fallback
console.error('Error opening options page:', chrome.runtime.lastError);
chrome.tabs.create({
url: chrome.runtime.getURL('options/options.html')
});
}
});
} catch (error) {
console.error('Failed to open options page:', error);
// Fallback: open in new tab
chrome.tabs.create({
url: chrome.runtime.getURL('options/options.html')
});
}
});
helpBtn.addEventListener('click', (e) => {
e.preventDefault();
chrome.tabs.create({
url: 'https://github.com/QwenLM/qwen-code/tree/main/packages/chrome-qwen-bridge'
});
});
// Helper functions
function showLoading(message) {
responseSection.style.display = 'block';
responseType.textContent = 'Loading';
responseContent.textContent = message;
responseSection.classList.add('loading');
}
function showResponse(type, content) {
responseSection.style.display = 'block';
responseType.textContent = type;
responseType.style.color = '#666';
responseContent.textContent = typeof content === 'string' ? content : JSON.stringify(content, null, 2);
responseSection.classList.remove('loading');
responseSection.classList.add('fade-in');
}
function showError(message) {
responseSection.style.display = 'block';
responseType.textContent = 'Error';
responseType.style.color = '#c00';
responseContent.textContent = message;
responseSection.classList.remove('loading');
}
// Listen for status updates from background
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.type === 'STATUS_UPDATE') {
updateConnectionStatus(message.status !== 'disconnected', message.status);
} else if (message.type === 'QWEN_EVENT') {
// Handle events from Qwen CLI
console.log('Qwen event received:', message.event);
// Could update UI based on event
}
});