feat: sidebar CSS inspector + per-tab agents (v0.13.9.0) (#650)

* feat: CDP inspector module — persistent sessions, CSS cascade, style modification

New browse/src/cdp-inspector.ts with full CDP inspection engine:
- inspectElement() via CSS.getMatchedStylesForNode + DOM.getBoxModel
- modifyStyle() via CSS.setStyleTexts with headless page.evaluate fallback
- Persistent CDP session lifecycle (create, reuse, detach on nav, re-create)
- Specificity sorting, overridden property detection, UA rule filtering
- Modification history with undo support
- formatInspectorResult() for CLI output

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: browse server inspector endpoints + inspect/style/cleanup/prettyscreenshot CLI

Server endpoints: POST /inspector/pick, GET /inspector, POST /inspector/apply,
POST /inspector/reset, GET /inspector/history, GET /inspector/events (SSE).
CLI commands: inspect (CDP cascade), style (live CSS mod), cleanup (page clutter
removal), prettyscreenshot (clean screenshot pipeline).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: sidebar CSS inspector — element picker, box model, rule cascade, quick edit

Extension changes for the visual CSS inspector:
- inspector.js: element picker with hover highlight, CSS selector generation,
  basic mode fallback (getComputedStyle + CSSOM), page alteration handlers
- inspector.css: picker overlay styles (blue highlight + tooltip)
- background.js: inspector message routing (picker <-> server <-> sidepanel)
- sidepanel: Inspector tab with box model viz (gstack palette), matched rules
  with specificity badges, computed styles, click-to-edit quick edit,
  Send to Agent/Code button, empty/loading/error states

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: document inspect, style, cleanup, prettyscreenshot browse commands

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: auto-track user-created tabs and handle tab close

browser-manager.ts changes:
- context.on('page') listener: automatically tracks tabs opened by the user
  (Cmd+T, right-click open in new tab, window.open). Previously only
  programmatic newTab() was tracked, so user tabs were invisible.
- page.on('close') handler in wirePageEvents: removes closed tabs from the
  pages map and switches activeTabId to the last remaining tab.
- syncActiveTabByUrl: match Chrome extension's active tab URL to the correct
  Playwright page for accurate tab identity.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: per-tab agent isolation via BROWSE_TAB environment variable

Prevents parallel sidebar agents from interfering with each other's tab context.

Three-layer fix:
- sidebar-agent.ts: passes BROWSE_TAB=<tabId> env var to each claude process,
  per-tab processing set allows concurrent agents across tabs
- cli.ts: reads process.env.BROWSE_TAB and includes tabId in command request body
- server.ts: handleCommand() temporarily switches activeTabId when tabId is present,
  restores after command completes (safe: Bun event loop is single-threaded)

Also: per-tab agent state (TabAgentState map), per-tab message queuing,
per-tab chat buffers, verbose streaming narration, stop button endpoint.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: sidebar per-tab chat context, tab bar sync, stop button, UX polish

Extension changes:
- sidepanel.js: per-tab chat history (tabChatHistories map), switchChatTab()
  swaps entire chat view, browserTabActivated handler for instant tab sync,
  stop button wired to /sidebar-agent/stop, pollTabs renders tab bar
- sidepanel.html: updated banner text ("Browser co-pilot"), stop button markup,
  input placeholder "Ask about this page..."
- sidepanel.css: tab bar styles, stop button styles, loading state fixes
- background.js: chrome.tabs.onActivated sends browserTabActivated to sidepanel
  with tab URL for instant tab switch detection

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: per-tab isolation, BROWSE_TAB pinning, tab tracking, sidebar UX

sidebar-agent.test.ts (new tests):
- BROWSE_TAB env var passed to claude process
- CLI reads BROWSE_TAB and sends tabId in body
- handleCommand accepts tabId, saves/restores activeTabId
- Tab pinning only activates when tabId provided
- Per-tab agent state, queue, concurrency
- processingTabs set for parallel agents

sidebar-ux.test.ts (new tests):
- context.on('page') tracks user-created tabs
- page.on('close') removes tabs from pages map
- Tab isolation uses BROWSE_TAB not system prompt hack
- Per-tab chat context in sidepanel
- Tab bar rendering, stop button, banner text

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: resolve merge conflicts — keep security defenses + per-tab isolation

Merged main's security improvements (XML escaping, prompt injection defense,
allowed commands whitelist, --model opus, Write tool, stderr capture) with
our branch's per-tab isolation (BROWSE_TAB env var, processingTabs set,
no --resume). Updated test expectations for expanded system prompt.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* chore: bump version and changelog (v0.13.9.0)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: add inspector message types to background.js allowlist

Pre-existing bug found by Codex: ALLOWED_TYPES in background.js was missing
all inspector message types (startInspector, stopInspector, elementPicked,
pickerCancelled, applyStyle, toggleClass, injectCSS, resetAll, inspectResult).
Messages were silently rejected, making the inspector broken on ALL pages.

Also: separate executeScript and insertCSS into individual try blocks in
injectInspector(), store inspectorMode for routing, and add content.js
fallback when script injection fails (CSP, chrome:// pages).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: basic element picker in content.js for CSP-restricted pages

When inspector.js can't be injected (CSP, chrome:// pages), content.js
provides a basic picker using getComputedStyle + CSSOM:
- startBasicPicker/stopBasicPicker message handlers
- captureBasicData() with ~30 key CSS properties, box model, matched rules
- Hover highlight with outline save/restore (never leaves artifacts)
- Click uses e.target directly (no re-querying by selector)
- Sends inspectResult with mode:'basic' for sidebar rendering
- Escape key cancels picker and restores outlines

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: cleanup + screenshot buttons in sidebar inspector toolbar

Two action buttons in the inspector toolbar:
- Cleanup (🧹): POSTs cleanup --all to server, shows spinner, chat
  notification on success, resets inspector state (element may be removed)
- Screenshot (📸): POSTs screenshot to server, shows spinner, chat
  notification with saved file path

Shared infrastructure:
- .inspector-action-btn CSS with loading spinner via ::after pseudo-element
- chat-notification type in addChatEntry() for system messages
- package.json version bump to 0.13.9.0

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: inspector allowlist, CSP fallback, cleanup/screenshot buttons

16 new tests in sidebar-ux.test.ts:
- Inspector message allowlist includes all inspector types
- content.js basic picker (startBasicPicker, captureBasicData, CSSOM,
  outline save/restore, inspectResult with mode basic, Escape cleanup)
- background.js CSP fallback (separate try blocks, inspectorMode, fallback)
- Cleanup button (POST /command, inspector reset after success)
- Screenshot button (POST /command, notification rendering)
- Chat notification type and CSS styles

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* docs: update project documentation for v0.13.9.0

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: cleanup + screenshot buttons in chat toolbar (not just inspector)

Quick actions toolbar (🧹 Cleanup, 📸 Screenshot) now appears above the chat
input, always visible. Both inspector and chat buttons share runCleanup() and
runScreenshot() helper functions. Clicking either set shows loading state on
both simultaneously.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: chat toolbar buttons, shared helpers, quick-action-btn styles

Tests that chat toolbar exists (chat-cleanup-btn, chat-screenshot-btn,
quick-actions container), CSS styles (.quick-action-btn, .quick-action-btn.loading),
shared runCleanup/runScreenshot helper functions, and cleanup inspector reset.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: aggressive cleanup heuristics — overlays, scroll unlock, blur removal

Massively expanded CLEANUP_SELECTORS with patterns from uBlock Origin and
Readability.js research:
- ads: 30+ selectors (Google, Amazon, Outbrain, Taboola, Criteo, etc.)
- cookies: OneTrust, Cookiebot, TrustArc, Quantcast + generic patterns
- overlays (NEW): paywalls, newsletter popups, interstitials, push prompts,
  app download banners, survey modals
- social: follow prompts, share tools
- Cleanup now defaults to --all when no args (sidebar button fix)
- Uses !important on all display:none (overrides inline styles)
- Unlocks body/html scroll (overflow:hidden from modal lockout)
- Removes blur/filter effects (paywall content blur)
- Removes max-height truncation (article teaser truncation)
- Collapses empty ad placeholder whitespace (empty divs after ad removal)
- Skips gstack-ctrl indicator in sticky removal

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: disable action buttons when disconnected, no error spam

- setActionButtonsEnabled() toggles .disabled class on all cleanup/screenshot
  buttons (both chat toolbar and inspector toolbar)
- Called with false in updateConnection when server URL is null
- Called with true when connection established
- runCleanup/runScreenshot silently return when disconnected instead of
  showing 'Not connected' error notifications
- CSS .disabled style: pointer-events:none, opacity:0.3, cursor:not-allowed

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: cleanup heuristics, button disabled state, overlay selectors

17 new tests:
- cleanup defaults to --all on empty args
- CLEANUP_SELECTORS overlays category (paywall, newsletter, interstitial)
- Major ad networks in selectors (doubleclick, taboola, criteo, etc.)
- Major consent frameworks (OneTrust, Cookiebot, TrustArc, Quantcast)
- !important override for inline styles
- Scroll unlock (body overflow:hidden)
- Blur removal (paywall content blur)
- Article truncation removal (max-height)
- Empty placeholder collapse
- gstack-ctrl indicator skip in sticky cleanup
- setActionButtonsEnabled function
- Buttons disabled when disconnected
- No error spam from cleanup/screenshot when disconnected
- CSS disabled styles for action buttons

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: LLM-based page cleanup — agent analyzes page semantically

Instead of brittle CSS selectors, the cleanup button now sends a prompt to
the sidebar agent (which IS an LLM). The agent:
1. Runs deterministic $B cleanup --all as a quick first pass
2. Takes a snapshot to see what's left
3. Analyzes the page semantically to identify remaining clutter
4. Removes elements intelligently, preserving site branding

This means cleanup works correctly on any site without site-specific selectors.
The LLM understands that "Your Daily Puzzles" is clutter, "ADVERTISEMENT" is
junk, but the SF Chronicle masthead should stay.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* feat: aggressive cleanup heuristics + preserve top nav bar

Deterministic cleanup improvements (used as first pass before LLM analysis):
- New 'clutter' category: audio players, podcast widgets, sidebar puzzles/games,
  recirculation widgets (taboola, outbrain, nativo), cross-promotion banners
- Text-content detection: removes "ADVERTISEMENT", "Article continues below",
  "Sponsored", "Paid content" labels and their parent wrappers
- Sticky fix: preserves the topmost full-width element near viewport top (site
  nav bar) instead of hiding all sticky/fixed elements. Sorts by vertical
  position, preserves the first one that spans >80% viewport width.

Tests: clutter category, ad label removal, nav bar preservation logic.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: LLM-based cleanup architecture, deterministic heuristics, sticky nav

22 new tests covering:
- Cleanup button uses /sidebar-command (agent) not /command (deterministic)
- Cleanup prompt includes deterministic first pass + agent snapshot analysis
- Cleanup prompt lists specific clutter categories for agent guidance
- Cleanup prompt preserves site identity (masthead, headline, body, byline)
- Cleanup prompt instructs scroll unlock and $B eval removal
- Loading state management (async agent, setTimeout)
- Deterministic clutter: audio/podcast, games/puzzles, recirculation
- Ad label text patterns (ADVERTISEMENT, Sponsored, Article continues)
- Ad label parent wrapper hiding for small containers
- Sticky nav preservation (sort by position, first full-width near top)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: prevent repeat chat message rendering on reconnect/replay

Root cause: server persists chat to disk (chat.jsonl) and replays on restart.
Client had no dedup, so every reconnect re-rendered the entire history.
Messages from an old HN session would repeat endlessly on the SF Chronicle tab.

Fix: renderedEntryIds Set tracks which entry IDs have been rendered. addChatEntry
skips entries already in the set. Entries without an id (local notifications)
bypass the check. Clear chat resets the set.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: agent stops when done, no focus stealing, opus for prompt injection safety

Three fixes for sidebar agent UX:
- System prompt: "Be CONCISE. STOP as soon as the task is done. Do NOT keep
  exploring or doing bonus work." Prevents agent from endlessly taking
  screenshots and highlighting elements after answering the question.
- switchTab(id, opts): new bringToFront option. Internal tab pinning
  (BROWSE_TAB) uses bringToFront: false so agent commands never steal
  window focus from the user's active app.
- Keep opus model (not sonnet) for prompt injection resistance on untrusted
  web pages. Remove Write from allowedTools (agent only needs Bash for $B).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: agent conciseness, focus stealing, opus model, switchTab opts

Tests for the three UX fixes:
- System prompt contains STOP/CONCISE/Do NOT keep exploring
- sidebar agent uses opus (not sonnet) for prompt injection resistance
- switchTab has bringToFront option, defaults to true (opt-out)
- handleCommand tab pinning uses bringToFront: false (no focus steal)
- Updated stale tests: switchTab signature, allowedTools excludes Write,
  narration -> conciseness, tab pinning restore calls

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* test: sidebar CSS interaction E2E — HN comment highlight round-trip

New E2E test (periodic tier, ~$2/run) that exercises the full sidebar
agent pipeline with CSS interaction:
1. Agent navigates to Hacker News
2. Clicks into the top story's comments
3. Reads comments and identifies the most insightful one
4. Highlights it with a 4px solid orange outline via style injection

Tests: navigation, snapshot, text reading, LLM judgment, CSS modification.
Requires real browser + real Claude (ANTHROPIC_API_KEY).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

* fix: sidebar CSS E2E test — correct idle timeout (ms not s), pipe stdio

Root cause of test failure: BROWSE_IDLE_TIMEOUT is in milliseconds, not
seconds. '600' = 0.6 seconds, server died immediately after health check.
Fixed to '600000' (10 minutes).

Also: use 'pipe' stdio instead of file descriptors (closing fds kills child
on macOS/bun), catch ConnectionRefused on poll retry, 4 min poll timeout
for the multi-step opus task.

Test passes: agent navigates to HN, reads comments, identifies most
insightful one, highlights it with orange CSS, stops. 114s, $0.00.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Garry Tan
2026-03-30 12:51:05 -06:00
committed by GitHub
parent 7911b7b974
commit a1a933614c
31 changed files with 6178 additions and 132 deletions
+168 -1
View File
@@ -158,6 +158,90 @@ async function fetchAndRelayRefs() {
} catch {}
}
// ─── Inspector ──────────────────────────────────────────────────
// Track inspector mode per tab — 'full' (inspector.js injected) or 'basic' (content.js fallback)
let inspectorMode = 'full';
async function injectInspector(tabId) {
// Try full inspector injection first
try {
await chrome.scripting.executeScript({
target: { tabId, allFrames: true },
files: ['inspector.js'],
});
// CSS injection failure alone doesn't need fallback
try {
await chrome.scripting.insertCSS({
target: { tabId, allFrames: true },
files: ['inspector.css'],
});
} catch {}
// Send startPicker to the injected inspector.js
try {
await chrome.tabs.sendMessage(tabId, { type: 'startPicker' });
} catch {}
inspectorMode = 'full';
return { ok: true, mode: 'full' };
} catch {
// Script injection failed (CSP, chrome:// page, etc.)
// Fall back to content.js basic picker (loaded by manifest on most pages)
try {
await chrome.tabs.sendMessage(tabId, { type: 'startBasicPicker' });
inspectorMode = 'basic';
return { ok: true, mode: 'basic' };
} catch {
inspectorMode = 'full';
return { error: 'Cannot inspect this page' };
}
}
}
async function stopInspector(tabId) {
try {
await chrome.tabs.sendMessage(tabId, { type: 'stopPicker' });
} catch {}
return { ok: true };
}
async function postInspectorPick(selector, frameInfo, basicData, activeTabUrl) {
const base = getBaseUrl();
if (!base || !authToken) {
// No browse server — return basic data as fallback
return { mode: 'basic', selector, basicData, frameInfo };
}
try {
const resp = await fetch(`${base}/inspector/pick`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${authToken}`,
},
body: JSON.stringify({ selector, activeTabUrl, frameInfo }),
signal: AbortSignal.timeout(10000),
});
if (!resp.ok) {
// Server error — fall back to basic mode
return { mode: 'basic', selector, basicData, frameInfo };
}
const data = await resp.json();
return { mode: 'cdp', ...data };
} catch {
// No server or timeout — fall back to basic mode
return { mode: 'basic', selector, basicData, frameInfo };
}
}
async function sendToContentScript(tabId, message) {
try {
const response = await chrome.tabs.sendMessage(tabId, message);
return response || { ok: true };
} catch {
return { error: 'Content script not available' };
}
}
// ─── Message Handling ──────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
@@ -169,7 +253,11 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
const ALLOWED_TYPES = new Set([
'getPort', 'setPort', 'getServerUrl', 'fetchRefs',
'openSidePanel', 'command', 'sidebar-command'
'openSidePanel', 'command', 'sidebar-command',
// Inspector message types
'startInspector', 'stopInspector', 'elementPicked', 'pickerCancelled',
'applyStyle', 'toggleClass', 'injectCSS', 'resetAll',
'inspectResult'
]);
if (!ALLOWED_TYPES.has(msg.type)) {
console.warn('[gstack] Rejected unknown message type:', msg.type);
@@ -209,6 +297,69 @@ chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
return;
}
// Inspector: inject + start picker
if (msg.type === 'startInspector') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs?.[0]?.id;
if (!tabId) { sendResponse({ error: 'No active tab' }); return; }
injectInspector(tabId).then(result => sendResponse(result));
});
return true;
}
// Inspector: stop picker
if (msg.type === 'stopInspector') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs?.[0]?.id;
if (!tabId) { sendResponse({ error: 'No active tab' }); return; }
stopInspector(tabId).then(result => sendResponse(result));
});
return true;
}
// Inspector: element picked by content script
if (msg.type === 'elementPicked') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const activeTabUrl = tabs?.[0]?.url || null;
const frameInfo = msg.frameSrc ? { frameSrc: msg.frameSrc, frameName: msg.frameName } : null;
postInspectorPick(msg.selector, frameInfo, msg.basicData, activeTabUrl)
.then(result => {
// Forward enriched result to sidepanel
chrome.runtime.sendMessage({
type: 'inspectResult',
data: {
...result,
selector: msg.selector,
tagName: msg.tagName,
classes: msg.classes,
id: msg.id,
dimensions: msg.dimensions,
basicData: msg.basicData,
frameInfo,
},
}).catch(() => {});
sendResponse({ ok: true });
});
});
return true;
}
// Inspector: picker cancelled
if (msg.type === 'pickerCancelled') {
chrome.runtime.sendMessage({ type: 'pickerCancelled' }).catch(() => {});
return;
}
// Inspector: route alteration commands to content script
if (msg.type === 'applyStyle' || msg.type === 'toggleClass' || msg.type === 'injectCSS' || msg.type === 'resetAll') {
chrome.tabs.query({ active: true, currentWindow: true }, (tabs) => {
const tabId = tabs?.[0]?.id;
if (!tabId) { sendResponse({ error: 'No active tab' }); return; }
sendToContentScript(tabId, msg).then(result => sendResponse(result));
});
return true;
}
// Sidebar → browse server command proxy
if (msg.type === 'command') {
executeCommand(msg.command, msg.args).then(result => sendResponse(result));
@@ -263,6 +414,22 @@ chrome.runtime.onInstalled.addListener(async () => {
}, 1000);
});
// ─── Tab Switch Detection ────────────────────────────────────────
// Notify sidepanel instantly when the user switches tabs in the browser.
// This is faster than polling — the sidebar swaps chat context immediately.
chrome.tabs.onActivated.addListener((activeInfo) => {
chrome.tabs.get(activeInfo.tabId, (tab) => {
if (chrome.runtime.lastError || !tab) return;
chrome.runtime.sendMessage({
type: 'browserTabActivated',
tabId: activeInfo.tabId,
url: tab.url || '',
title: tab.title || '',
}).catch(() => {}); // sidepanel may not be open
});
});
// ─── Startup ────────────────────────────────────────────────────
// Load auth token BEFORE first health poll (token no longer in /health response)
+209
View File
@@ -125,8 +125,217 @@ function renderRefPanel(refs) {
container.appendChild(panel);
}
// ─── Basic Inspector Picker (CSP fallback) ──────────────────
// When inspector.js can't be injected (CSP, chrome:// pages), content.js
// provides a basic element picker using getComputedStyle + CSSOM.
let basicPickerActive = false;
let basicPickerOverlay = null;
let basicPickerLastEl = null;
let basicPickerSavedOutline = '';
const BASIC_KEY_PROPERTIES = [
'display', 'position', 'top', 'right', 'bottom', 'left',
'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height',
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
'color', 'background-color', 'background-image',
'font-family', 'font-size', 'font-weight', 'line-height',
'text-align', 'text-decoration',
'overflow', 'overflow-x', 'overflow-y',
'opacity', 'z-index',
'flex-direction', 'justify-content', 'align-items', 'flex-wrap', 'gap',
'grid-template-columns', 'grid-template-rows',
'box-shadow', 'border-radius', 'transform',
];
function captureBasicData(el) {
const computed = getComputedStyle(el);
const rect = el.getBoundingClientRect();
const computedStyles = {};
for (const prop of BASIC_KEY_PROPERTIES) {
computedStyles[prop] = computed.getPropertyValue(prop);
}
const boxModel = {
content: { width: rect.width, height: rect.height },
padding: {
top: parseFloat(computed.paddingTop) || 0,
right: parseFloat(computed.paddingRight) || 0,
bottom: parseFloat(computed.paddingBottom) || 0,
left: parseFloat(computed.paddingLeft) || 0,
},
border: {
top: parseFloat(computed.borderTopWidth) || 0,
right: parseFloat(computed.borderRightWidth) || 0,
bottom: parseFloat(computed.borderBottomWidth) || 0,
left: parseFloat(computed.borderLeftWidth) || 0,
},
margin: {
top: parseFloat(computed.marginTop) || 0,
right: parseFloat(computed.marginRight) || 0,
bottom: parseFloat(computed.marginBottom) || 0,
left: parseFloat(computed.marginLeft) || 0,
},
};
// Matched CSS rules via CSSOM (same-origin only)
const matchedRules = [];
try {
for (const sheet of document.styleSheets) {
try {
const rules = sheet.cssRules || sheet.rules;
if (!rules) continue;
for (const rule of rules) {
if (rule.type !== CSSRule.STYLE_RULE) continue;
try {
if (el.matches(rule.selectorText)) {
const properties = [];
for (let i = 0; i < rule.style.length; i++) {
const prop = rule.style[i];
properties.push({
name: prop,
value: rule.style.getPropertyValue(prop),
priority: rule.style.getPropertyPriority(prop),
});
}
matchedRules.push({
selector: rule.selectorText,
properties,
source: sheet.href || 'inline',
});
}
} catch { /* skip rules that can't be matched */ }
}
} catch { /* cross-origin sheet — silently skip */ }
}
} catch { /* CSSOM not available */ }
return { computedStyles, boxModel, matchedRules };
}
function basicBuildSelector(el) {
if (el.id) {
const sel = '#' + CSS.escape(el.id);
try { if (document.querySelectorAll(sel).length === 1) return sel; } catch {}
}
const parts = [];
let current = el;
while (current && current !== document.body && current !== document.documentElement) {
let part = current.tagName.toLowerCase();
if (current.id) {
parts.unshift('#' + CSS.escape(current.id));
break;
}
if (current.className && typeof current.className === 'string') {
const classes = current.className.trim().split(/\s+/).filter(c => c.length > 0);
if (classes.length > 0) part += '.' + classes.map(c => CSS.escape(c)).join('.');
}
const parent = current.parentElement;
if (parent) {
const siblings = Array.from(parent.children).filter(s => s.tagName === current.tagName);
if (siblings.length > 1) {
part += `:nth-child(${Array.from(parent.children).indexOf(current) + 1})`;
}
}
parts.unshift(part);
current = current.parentElement;
}
return parts.join(' > ');
}
function basicPickerHighlight(el) {
// Restore previous element
if (basicPickerLastEl && basicPickerLastEl !== el) {
basicPickerLastEl.style.outline = basicPickerSavedOutline;
}
if (el) {
basicPickerSavedOutline = el.style.outline;
el.style.outline = '2px solid rgba(59, 130, 246, 0.6)';
basicPickerLastEl = el;
}
}
function basicPickerCleanup() {
if (basicPickerLastEl) {
basicPickerLastEl.style.outline = basicPickerSavedOutline;
basicPickerLastEl = null;
basicPickerSavedOutline = '';
}
basicPickerActive = false;
document.removeEventListener('mousemove', onBasicMouseMove, true);
document.removeEventListener('click', onBasicClick, true);
document.removeEventListener('keydown', onBasicKeydown, true);
}
function onBasicMouseMove(e) {
if (!basicPickerActive) return;
e.preventDefault();
e.stopPropagation();
const el = document.elementFromPoint(e.clientX, e.clientY);
if (el && el !== basicPickerLastEl) {
basicPickerHighlight(el);
}
}
function onBasicClick(e) {
if (!basicPickerActive) return;
e.preventDefault();
e.stopPropagation();
const el = e.target;
const basicData = captureBasicData(el);
const selector = basicBuildSelector(el);
const tagName = el.tagName.toLowerCase();
const id = el.id || null;
const classes = el.className && typeof el.className === 'string'
? el.className.trim().split(/\s+/).filter(c => c.length > 0)
: [];
basicPickerCleanup();
chrome.runtime.sendMessage({
type: 'inspectResult',
data: {
selector,
tagName,
id,
classes,
basicData,
mode: 'basic',
boxModel: basicData.boxModel,
computedStyles: basicData.computedStyles,
matchedRules: basicData.matchedRules,
},
});
}
function onBasicKeydown(e) {
if (e.key === 'Escape') {
basicPickerCleanup();
chrome.runtime.sendMessage({ type: 'pickerCancelled' });
}
}
function startBasicPicker() {
basicPickerActive = true;
document.addEventListener('mousemove', onBasicMouseMove, true);
document.addEventListener('click', onBasicClick, true);
document.addEventListener('keydown', onBasicKeydown, true);
}
// Listen for messages from background worker
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'startBasicPicker') {
startBasicPicker();
return;
}
if (msg.type === 'stopBasicPicker') {
basicPickerCleanup();
return;
}
if (msg.type === 'refs' && msg.data) {
const refs = msg.data.refs || [];
const mode = msg.data.mode;
+29
View File
@@ -0,0 +1,29 @@
/* gstack browse — CSS Inspector overlay styles
* Injected alongside inspector.js into the active tab.
* Design system: amber accent, zinc neutrals.
*/
#gstack-inspector-highlight {
position: fixed;
pointer-events: none;
z-index: 2147483647;
background: rgba(59, 130, 246, 0.15);
border: 2px solid rgba(59, 130, 246, 0.6);
border-radius: 2px;
transition: top 50ms ease, left 50ms ease, width 50ms ease, height 50ms ease;
}
#gstack-inspector-tooltip {
position: fixed;
pointer-events: none;
z-index: 2147483647;
background: #27272A;
color: #e0e0e0;
font-family: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
font-size: 11px;
padding: 3px 8px;
border-radius: 4px;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.4);
line-height: 18px;
}
+459
View File
@@ -0,0 +1,459 @@
/**
* gstack browse — CSS Inspector content script
*
* Dynamically injected via chrome.scripting.executeScript.
* Provides element picker, selector generation, basic computed style capture,
* and page alteration handlers for agent-pushed CSS changes.
*/
(() => {
// Guard against double-injection
if (window.__gstackInspectorActive) return;
window.__gstackInspectorActive = true;
// ─── State ──────────────────────────────────────────────────────
let pickerActive = false;
let highlightEl = null;
let tooltipEl = null;
let lastPickTime = 0;
const PICK_DEBOUNCE_MS = 200;
// Track original inline styles for resetAll
const originalStyles = new Map(); // element -> Map<property, value>
const injectedStyleIds = new Set();
// ─── Highlight Overlay ──────────────────────────────────────────
function createHighlight() {
if (highlightEl) return;
highlightEl = document.createElement('div');
highlightEl.id = 'gstack-inspector-highlight';
highlightEl.style.cssText = `
position: fixed;
pointer-events: none;
z-index: 2147483647;
background: rgba(59, 130, 246, 0.15);
border: 2px solid rgba(59, 130, 246, 0.6);
border-radius: 2px;
transition: top 50ms, left 50ms, width 50ms, height 50ms;
`;
document.documentElement.appendChild(highlightEl);
tooltipEl = document.createElement('div');
tooltipEl.id = 'gstack-inspector-tooltip';
tooltipEl.style.cssText = `
position: fixed;
pointer-events: none;
z-index: 2147483647;
background: #27272A;
color: #e0e0e0;
font-family: 'JetBrains Mono', 'SF Mono', 'Fira Code', monospace;
font-size: 11px;
padding: 3px 8px;
border-radius: 4px;
white-space: nowrap;
box-shadow: 0 2px 8px rgba(0,0,0,0.4);
display: none;
`;
document.documentElement.appendChild(tooltipEl);
}
function removeHighlight() {
if (highlightEl) { highlightEl.remove(); highlightEl = null; }
if (tooltipEl) { tooltipEl.remove(); tooltipEl = null; }
}
function updateHighlight(el) {
if (!highlightEl || !tooltipEl) return;
const rect = el.getBoundingClientRect();
highlightEl.style.top = rect.top + 'px';
highlightEl.style.left = rect.left + 'px';
highlightEl.style.width = rect.width + 'px';
highlightEl.style.height = rect.height + 'px';
highlightEl.style.display = 'block';
// Build tooltip text: <tag> .classes WxH
const tag = el.tagName.toLowerCase();
const classes = el.className && typeof el.className === 'string'
? '.' + el.className.trim().split(/\s+/).join('.')
: '';
const dims = `${Math.round(rect.width)}x${Math.round(rect.height)}`;
tooltipEl.textContent = `<${tag}> ${classes} ${dims}`.trim();
// Position tooltip above element, or below if no room
const tooltipHeight = 24;
const gap = 6;
let tooltipTop = rect.top - tooltipHeight - gap;
if (tooltipTop < 4) tooltipTop = rect.bottom + gap;
let tooltipLeft = rect.left;
if (tooltipLeft < 4) tooltipLeft = 4;
tooltipEl.style.top = tooltipTop + 'px';
tooltipEl.style.left = tooltipLeft + 'px';
tooltipEl.style.display = 'block';
}
// ─── Selector Generation ────────────────────────────────────────
function buildSelector(el) {
// If element has an id, use it directly
if (el.id) {
const sel = '#' + CSS.escape(el.id);
if (isUnique(sel)) return sel;
}
// Build path from element up to nearest ancestor with id or body
const parts = [];
let current = el;
while (current && current !== document.body && current !== document.documentElement) {
let part = current.tagName.toLowerCase();
// If current has an id, use it and stop
if (current.id) {
part = '#' + CSS.escape(current.id);
parts.unshift(part);
break;
}
// Add classes
if (current.className && typeof current.className === 'string') {
const classes = current.className.trim().split(/\s+/).filter(c => c.length > 0);
if (classes.length > 0) {
part += '.' + classes.map(c => CSS.escape(c)).join('.');
}
}
// Add nth-child if needed to disambiguate
const parent = current.parentElement;
if (parent) {
const siblings = Array.from(parent.children).filter(
s => s.tagName === current.tagName
);
if (siblings.length > 1) {
const idx = siblings.indexOf(current) + 1;
part += `:nth-child(${Array.from(parent.children).indexOf(current) + 1})`;
}
}
parts.unshift(part);
current = current.parentElement;
}
// If we didn't reach an id, prepend body
if (parts.length > 0 && !parts[0].startsWith('#')) {
// Don't prepend body, just use the path as-is
}
const selector = parts.join(' > ');
// Verify uniqueness
if (isUnique(selector)) return selector;
// Fallback: add nth-child at each level until unique
return selector;
}
function isUnique(selector) {
try {
return document.querySelectorAll(selector).length === 1;
} catch {
return false;
}
}
// ─── Basic Mode Data Capture ────────────────────────────────────
const KEY_PROPERTIES = [
'display', 'position', 'top', 'right', 'bottom', 'left',
'width', 'height', 'min-width', 'max-width', 'min-height', 'max-height',
'margin-top', 'margin-right', 'margin-bottom', 'margin-left',
'padding-top', 'padding-right', 'padding-bottom', 'padding-left',
'border-top-width', 'border-right-width', 'border-bottom-width', 'border-left-width',
'border-top-style', 'border-right-style', 'border-bottom-style', 'border-left-style',
'border-top-color', 'border-right-color', 'border-bottom-color', 'border-left-color',
'color', 'background-color', 'background-image',
'font-family', 'font-size', 'font-weight', 'line-height', 'letter-spacing',
'text-align', 'text-decoration', 'text-transform',
'overflow', 'overflow-x', 'overflow-y',
'opacity', 'z-index',
'flex-direction', 'justify-content', 'align-items', 'flex-wrap', 'gap',
'grid-template-columns', 'grid-template-rows',
'box-shadow', 'border-radius',
'transition', 'transform',
];
function captureBasicData(el) {
const computed = getComputedStyle(el);
const rect = el.getBoundingClientRect();
// Capture key computed properties
const computedStyles = {};
for (const prop of KEY_PROPERTIES) {
computedStyles[prop] = computed.getPropertyValue(prop);
}
// Box model from computed
const boxModel = {
content: { width: rect.width, height: rect.height },
padding: {
top: parseFloat(computed.paddingTop) || 0,
right: parseFloat(computed.paddingRight) || 0,
bottom: parseFloat(computed.paddingBottom) || 0,
left: parseFloat(computed.paddingLeft) || 0,
},
border: {
top: parseFloat(computed.borderTopWidth) || 0,
right: parseFloat(computed.borderRightWidth) || 0,
bottom: parseFloat(computed.borderBottomWidth) || 0,
left: parseFloat(computed.borderLeftWidth) || 0,
},
margin: {
top: parseFloat(computed.marginTop) || 0,
right: parseFloat(computed.marginRight) || 0,
bottom: parseFloat(computed.marginBottom) || 0,
left: parseFloat(computed.marginLeft) || 0,
},
};
// Matched CSS rules via CSSOM (same-origin only)
const matchedRules = [];
try {
for (const sheet of document.styleSheets) {
try {
const rules = sheet.cssRules || sheet.rules;
if (!rules) continue;
for (const rule of rules) {
if (rule.type !== CSSRule.STYLE_RULE) continue;
try {
if (el.matches(rule.selectorText)) {
const properties = [];
for (let i = 0; i < rule.style.length; i++) {
const prop = rule.style[i];
properties.push({
name: prop,
value: rule.style.getPropertyValue(prop),
priority: rule.style.getPropertyPriority(prop),
});
}
matchedRules.push({
selector: rule.selectorText,
properties,
source: sheet.href || 'inline',
});
}
} catch { /* skip rules that can't be matched */ }
}
} catch { /* cross-origin sheet — silently skip */ }
}
} catch { /* CSSOM not available */ }
return { computedStyles, boxModel, matchedRules };
}
// ─── Picker Event Handlers ──────────────────────────────────────
function onMouseMove(e) {
if (!pickerActive) return;
// Ignore our own overlay elements
const target = e.target;
if (target === highlightEl || target === tooltipEl) return;
if (target.id === 'gstack-inspector-highlight' || target.id === 'gstack-inspector-tooltip') return;
updateHighlight(target);
}
function onClick(e) {
if (!pickerActive) return;
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
// Debounce
const now = Date.now();
if (now - lastPickTime < PICK_DEBOUNCE_MS) return;
lastPickTime = now;
const target = e.target;
if (target === highlightEl || target === tooltipEl) return;
if (target.id === 'gstack-inspector-highlight' || target.id === 'gstack-inspector-tooltip') return;
const selector = buildSelector(target);
const basicData = captureBasicData(target);
// Frame detection
const frameInfo = {};
if (window !== window.top) {
try {
frameInfo.frameSrc = window.location.href;
frameInfo.frameName = window.name || null;
} catch { /* cross-origin frame */ }
}
chrome.runtime.sendMessage({
type: 'elementPicked',
selector,
tagName: target.tagName.toLowerCase(),
classes: target.className && typeof target.className === 'string'
? target.className.trim().split(/\s+/).filter(c => c.length > 0)
: [],
id: target.id || null,
dimensions: {
width: Math.round(target.getBoundingClientRect().width),
height: Math.round(target.getBoundingClientRect().height),
},
basicData,
...frameInfo,
});
// Keep highlight on the picked element
}
function onKeyDown(e) {
if (!pickerActive) return;
if (e.key === 'Escape') {
e.preventDefault();
e.stopPropagation();
stopPicker();
chrome.runtime.sendMessage({ type: 'pickerCancelled' });
}
}
// ─── Picker Start/Stop ──────────────────────────────────────────
function startPicker() {
if (pickerActive) return;
pickerActive = true;
createHighlight();
document.addEventListener('mousemove', onMouseMove, true);
document.addEventListener('click', onClick, true);
document.addEventListener('keydown', onKeyDown, true);
}
function stopPicker() {
if (!pickerActive) return;
pickerActive = false;
removeHighlight();
document.removeEventListener('mousemove', onMouseMove, true);
document.removeEventListener('click', onClick, true);
document.removeEventListener('keydown', onKeyDown, true);
}
// ─── Page Alteration Handlers ───────────────────────────────────
function findElement(selector) {
try {
return document.querySelector(selector);
} catch {
return null;
}
}
function applyStyle(selector, property, value) {
// Validate property name: alphanumeric + hyphens only
if (!/^[a-zA-Z-]+$/.test(property)) return { error: 'Invalid property name' };
const el = findElement(selector);
if (!el) return { error: 'Element not found' };
// Track original value for resetAll
if (!originalStyles.has(el)) {
originalStyles.set(el, new Map());
}
const origMap = originalStyles.get(el);
if (!origMap.has(property)) {
origMap.set(property, el.style.getPropertyValue(property));
}
el.style.setProperty(property, value, 'important');
return { ok: true };
}
function toggleClass(selector, className, action) {
const el = findElement(selector);
if (!el) return { error: 'Element not found' };
if (action === 'add') {
el.classList.add(className);
} else if (action === 'remove') {
el.classList.remove(className);
} else {
el.classList.toggle(className);
}
return { ok: true };
}
function injectCSS(id, css) {
const styleId = `gstack-inject-${id}`;
let styleEl = document.getElementById(styleId);
if (!styleEl) {
styleEl = document.createElement('style');
styleEl.id = styleId;
document.head.appendChild(styleEl);
}
styleEl.textContent = css;
injectedStyleIds.add(styleId);
return { ok: true };
}
function resetAll() {
// Restore original inline styles
for (const [el, propMap] of originalStyles) {
for (const [prop, origVal] of propMap) {
if (origVal) {
el.style.setProperty(prop, origVal);
} else {
el.style.removeProperty(prop);
}
}
}
originalStyles.clear();
// Remove injected style elements
for (const id of injectedStyleIds) {
const el = document.getElementById(id);
if (el) el.remove();
}
injectedStyleIds.clear();
return { ok: true };
}
// ─── Message Listener ──────────────────────────────────────────
chrome.runtime.onMessage.addListener((msg, sender, sendResponse) => {
if (msg.type === 'startPicker') {
startPicker();
sendResponse({ ok: true });
return;
}
if (msg.type === 'stopPicker') {
stopPicker();
sendResponse({ ok: true });
return;
}
if (msg.type === 'applyStyle') {
const result = applyStyle(msg.selector, msg.property, msg.value);
sendResponse(result);
return;
}
if (msg.type === 'toggleClass') {
const result = toggleClass(msg.selector, msg.className, msg.action);
sendResponse(result);
return;
}
if (msg.type === 'injectCSS') {
const result = injectCSS(msg.id, msg.css);
sendResponse(result);
return;
}
if (msg.type === 'resetAll') {
const result = resetAll();
sendResponse(result);
return;
}
});
})();
+1 -1
View File
@@ -3,7 +3,7 @@
"name": "gstack browse",
"version": "0.1.0",
"description": "Live activity feed and @ref overlays for gstack browse",
"permissions": ["sidePanel", "storage", "activeTab"],
"permissions": ["sidePanel", "storage", "activeTab", "scripting"],
"host_permissions": ["http://127.0.0.1:*/"],
"action": {
"default_icon": {
+689 -17
View File
@@ -221,6 +221,13 @@ body::after {
color: #000;
border-bottom-right-radius: var(--radius-sm);
}
.chat-notification {
text-align: center;
font-size: 11px;
color: var(--text-meta);
padding: 4px 12px;
font-family: var(--font-mono);
}
.chat-bubble.assistant {
align-self: flex-start;
background: var(--bg-surface);
@@ -262,16 +269,27 @@ body::after {
}
.agent-tool {
display: flex;
align-items: center;
gap: 4px;
padding: 2px 6px;
background: var(--bg-base);
border: 1px solid var(--border-subtle);
border-radius: 3px;
font-size: 10px;
font-family: var(--font-mono);
overflow: hidden;
align-items: flex-start;
gap: 6px;
padding: 4px 8px;
background: rgba(245, 158, 11, 0.06);
border-left: 2px solid var(--amber-500);
border-radius: 0 4px 4px 0;
font-size: 12px;
font-family: var(--font-system);
margin: 2px 0;
}
.tool-icon {
flex-shrink: 0;
font-size: 11px;
line-height: 1.5;
}
.tool-description {
color: var(--text-body);
line-height: 1.5;
word-break: break-word;
}
/* Legacy classes kept for compat */
.tool-name {
color: var(--amber-500);
font-weight: 600;
@@ -285,9 +303,10 @@ body::after {
}
.agent-text {
color: var(--text-body);
font-size: 11px;
line-height: 1.4;
font-size: 12.5px;
line-height: 1.5;
word-break: break-word;
padding: 2px 0;
}
.agent-text pre {
background: var(--bg-base);
@@ -571,6 +590,65 @@ body::after {
}
/* ─── Command Bar ─────────────────────────────────────── */
/* ─── Quick Actions Toolbar ─────────────────────────────── */
.quick-actions {
display: flex;
gap: 6px;
padding: 4px 8px;
background: var(--bg-surface);
border-top: 1px solid var(--border-subtle);
flex-shrink: 0;
}
.quick-action-btn {
display: flex;
align-items: center;
gap: 4px;
height: 26px;
padding: 0 10px;
background: none;
border: 1px solid var(--zinc-600);
border-radius: var(--radius-sm);
color: var(--text-label);
font-family: var(--font-system);
font-size: 11px;
cursor: pointer;
transition: all 150ms;
}
.quick-action-btn:hover {
background: rgba(255, 255, 255, 0.05);
color: var(--text-body);
border-color: var(--zinc-400);
}
.quick-action-btn:active {
transform: scale(0.96);
}
.quick-action-btn.disabled, .inspector-action-btn.disabled {
pointer-events: none;
opacity: 0.3;
cursor: not-allowed;
}
.quick-action-btn.loading {
pointer-events: none;
opacity: 0.5;
}
.quick-action-btn.loading::after {
content: '';
display: inline-block;
width: 10px;
height: 10px;
border: 2px solid var(--zinc-600);
border-top-color: var(--amber-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
.command-bar {
display: flex;
align-items: center;
@@ -637,6 +715,22 @@ body::after {
opacity: 0.3;
cursor: not-allowed;
}
.stop-btn {
width: 26px;
height: 26px;
background: var(--error);
border: none;
border-radius: var(--radius-sm);
color: #fff;
font-size: 10px;
font-weight: 700;
cursor: pointer;
flex-shrink: 0;
line-height: 26px;
text-align: center;
}
.stop-btn:hover { background: #dc2626; }
.stop-btn:active { transform: scale(0.93); }
/* ─── Footer ──────────────────────────────────────────── */
footer {
@@ -686,17 +780,595 @@ footer {
/* ─── Experimental Banner ─────────────────────────────── */
.experimental-banner {
background: rgba(245, 158, 11, 0.15);
border: 1px solid rgba(245, 158, 11, 0.3);
color: #F59E0B;
padding: 8px 12px;
background: rgba(59, 130, 246, 0.08);
border: 1px solid rgba(59, 130, 246, 0.15);
color: var(--zinc-400);
padding: 6px 12px;
border-radius: 6px;
font-size: 12px;
margin: 8px 12px;
font-size: 11px;
margin: 6px 12px;
text-align: center;
flex-shrink: 0;
}
/* ─── Browser Tab Bar ─────────────────────────────────── */
.browser-tabs {
display: flex;
gap: 1px;
padding: 4px 8px;
background: var(--bg-base);
border-bottom: 1px solid var(--border);
overflow-x: auto;
flex-shrink: 0;
scrollbar-width: none;
}
.browser-tabs::-webkit-scrollbar { display: none; }
.browser-tab {
padding: 4px 10px;
font-size: 11px;
font-family: var(--font-system);
color: var(--text-meta);
background: transparent;
border: 1px solid transparent;
border-radius: var(--radius-sm);
cursor: pointer;
white-space: nowrap;
max-width: 140px;
overflow: hidden;
text-overflow: ellipsis;
flex-shrink: 0;
transition: background 100ms, color 100ms;
}
.browser-tab:hover {
background: var(--bg-hover);
color: var(--text-label);
}
.browser-tab.active {
background: var(--bg-surface);
color: var(--text-body);
border-color: var(--border);
}
/* ─── Inspector Tab ──────────────────────────────────── */
.inspector-toolbar {
display: flex;
align-items: center;
gap: 8px;
padding: 6px 10px;
background: var(--bg-surface);
border-bottom: 1px solid var(--border);
flex-shrink: 0;
}
.inspector-pick-btn {
display: flex;
align-items: center;
gap: 4px;
height: 28px;
padding: 0 10px;
background: none;
border: 1px solid var(--amber-500);
border-radius: var(--radius-sm);
color: var(--amber-500);
font-family: var(--font-system);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 150ms;
flex-shrink: 0;
}
.inspector-pick-btn:hover {
background: rgba(245, 158, 11, 0.1);
color: var(--amber-400);
}
.inspector-pick-btn.active {
background: var(--amber-500);
color: #000;
}
.inspector-pick-icon {
font-size: 14px;
line-height: 1;
}
/* ─── Action Buttons (Cleanup, Screenshot) ─────────────────── */
.inspector-action-btn {
display: flex;
align-items: center;
justify-content: center;
height: 28px;
width: 28px;
padding: 0;
background: none;
border: 1px solid var(--zinc-600);
border-radius: var(--radius-sm);
color: var(--text-label);
font-size: 14px;
cursor: pointer;
transition: all 150ms;
flex-shrink: 0;
}
.inspector-action-btn:hover {
background: rgba(255, 255, 255, 0.05);
color: var(--text-body);
border-color: var(--zinc-400);
}
.inspector-action-btn:active {
transform: scale(0.95);
}
.inspector-action-btn.loading {
pointer-events: none;
opacity: 0.5;
position: relative;
}
.inspector-action-btn.loading::after {
content: '';
position: absolute;
width: 12px;
height: 12px;
border: 2px solid var(--zinc-600);
border-top-color: var(--amber-400);
border-radius: 50%;
animation: spin 0.6s linear infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
.inspector-selected {
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-body);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
flex: 1;
min-width: 0;
}
.inspector-mode-badge {
font-family: var(--font-mono);
font-size: 10px;
padding: 1px 6px;
border-radius: var(--radius-sm);
flex-shrink: 0;
}
.inspector-mode-badge.basic {
background: var(--zinc-800);
color: var(--zinc-400);
}
.inspector-mode-badge.cdp {
background: rgba(34, 197, 94, 0.15);
color: var(--success);
}
/* Inspector content area */
.inspector-content {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
}
/* Empty state */
.inspector-empty {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 40px 24px;
text-align: center;
gap: 6px;
}
.inspector-empty-icon {
font-size: 24px;
color: var(--zinc-600);
margin-bottom: 4px;
}
.inspector-empty p {
color: var(--zinc-400);
font-size: 13px;
margin: 0;
}
.inspector-empty .muted {
color: var(--zinc-600);
font-size: 12px;
}
/* Loading state */
.inspector-loading {
padding: 16px 12px;
}
.inspector-loading-text {
font-size: 12px;
color: var(--amber-500);
margin-bottom: 12px;
animation: pulse 2s ease-in-out infinite;
}
.inspector-skeleton {
display: flex;
flex-direction: column;
gap: 8px;
}
.inspector-skeleton-bar {
height: 12px;
background: var(--zinc-800);
border-radius: var(--radius-sm);
animation: shimmer 1.5s ease-in-out infinite;
}
.inspector-skeleton-bar:nth-child(1) { width: 80%; }
.inspector-skeleton-bar:nth-child(2) { width: 60%; }
.inspector-skeleton-bar:nth-child(3) { width: 70%; }
@keyframes shimmer {
0%, 100% { opacity: 0.3; }
50% { opacity: 0.7; }
}
/* Error state */
.inspector-error {
padding: 16px 12px;
color: var(--error);
font-size: 12px;
font-family: var(--font-mono);
}
/* Inspector sections */
.inspector-section {
border-bottom: 1px solid var(--border-subtle);
}
.inspector-section-header {
font-family: var(--font-system);
font-size: 13px;
font-weight: 600;
color: var(--zinc-400);
padding: 8px 12px 4px;
}
.inspector-section-toggle {
display: flex;
align-items: center;
gap: 6px;
width: 100%;
padding: 8px 12px;
background: none;
border: none;
font-family: var(--font-system);
font-size: 13px;
font-weight: 600;
color: var(--zinc-400);
cursor: pointer;
text-align: left;
transition: color 150ms;
}
.inspector-section-toggle:hover {
color: var(--text-body);
}
.inspector-toggle-arrow {
font-size: 10px;
color: var(--zinc-400);
flex-shrink: 0;
width: 12px;
}
.inspector-section-body {
padding: 4px 12px 8px;
}
.inspector-section-body.collapsed {
display: none;
}
.inspector-rule-count {
font-size: 11px;
font-weight: 400;
color: var(--zinc-600);
margin-left: 4px;
}
.inspector-no-data {
color: var(--zinc-600);
font-size: 11px;
font-style: italic;
padding: 4px 0;
}
/* ─── Box Model ──────────────────────────────────────── */
.inspector-boxmodel {
padding: 8px 12px 12px;
}
.boxmodel-margin,
.boxmodel-border,
.boxmodel-padding,
.boxmodel-content {
position: relative;
display: flex;
align-items: center;
justify-content: center;
border: 1px dashed;
text-align: center;
}
.boxmodel-margin {
background: rgba(245, 158, 11, 0.08);
border-color: rgba(245, 158, 11, 0.3);
padding: 14px 20px;
border-radius: var(--radius-sm);
}
.boxmodel-border {
background: rgba(161, 161, 170, 0.08);
border-color: rgba(161, 161, 170, 0.3);
padding: 14px 20px;
width: 100%;
}
.boxmodel-padding {
background: rgba(34, 197, 94, 0.08);
border-color: rgba(34, 197, 94, 0.3);
padding: 14px 20px;
width: 100%;
}
.boxmodel-content {
background: rgba(59, 130, 246, 0.08);
border-color: rgba(59, 130, 246, 0.3);
padding: 8px 12px;
width: 100%;
min-height: 28px;
}
.boxmodel-content span {
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-body);
}
.boxmodel-label {
position: absolute;
top: 1px;
left: 4px;
font-family: var(--font-mono);
font-size: 10px;
color: var(--zinc-400);
pointer-events: none;
}
.boxmodel-value {
position: absolute;
font-family: var(--font-mono);
font-size: 11px;
color: var(--text-body);
}
.boxmodel-value.boxmodel-top { top: 1px; left: 50%; transform: translateX(-50%); }
.boxmodel-value.boxmodel-right { right: 4px; top: 50%; transform: translateY(-50%); }
.boxmodel-value.boxmodel-bottom { bottom: 1px; left: 50%; transform: translateX(-50%); }
.boxmodel-value.boxmodel-left { left: 4px; top: 50%; transform: translateY(-50%); }
/* ─── Matched Rules ──────────────────────────────────── */
.inspector-rule {
padding: 6px 0;
border-bottom: 1px solid var(--border-subtle);
}
.inspector-rule:last-child {
border-bottom: none;
}
.inspector-rule-header {
display: flex;
align-items: center;
justify-content: space-between;
gap: 8px;
margin-bottom: 2px;
}
.inspector-selector {
font-family: var(--font-mono);
font-size: 12px;
color: var(--amber-400);
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
max-width: 35ch;
}
.inspector-specificity {
font-family: var(--font-mono);
font-size: 10px;
background: var(--zinc-600);
color: var(--zinc-400);
padding: 0 4px;
border-radius: var(--radius-sm);
flex-shrink: 0;
}
.inspector-rule-props {
padding-left: 12px;
}
.inspector-prop {
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.6;
}
.inspector-prop.overridden {
text-decoration: line-through;
opacity: 0.5;
}
.inspector-prop-name {
color: var(--zinc-400);
}
.inspector-prop-value {
color: var(--text-body);
}
.inspector-important {
color: var(--error);
font-size: 10px;
}
.inspector-rule-source {
font-family: var(--font-mono);
font-size: 11px;
color: var(--zinc-600);
margin-top: 2px;
}
/* UA rules */
.inspector-ua-rules {
margin-top: 4px;
}
.inspector-ua-toggle {
display: flex;
align-items: center;
gap: 4px;
background: none;
border: none;
font-family: var(--font-mono);
font-size: 11px;
color: var(--zinc-600);
cursor: pointer;
padding: 4px 0;
transition: color 150ms;
}
.inspector-ua-toggle:hover {
color: var(--zinc-400);
}
.inspector-ua-body.collapsed {
display: none;
}
/* ─── Computed Styles ────────────────────────────────── */
.inspector-computed-row {
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.6;
padding: 0 0 0 4px;
}
.inspector-computed-row .inspector-prop-name {
color: var(--zinc-400);
}
.inspector-computed-row .inspector-prop-value {
color: var(--text-body);
}
/* ─── Quick Edit ─────────────────────────────────────── */
.inspector-quickedit-list {
display: flex;
flex-direction: column;
gap: 2px;
}
.inspector-quickedit-row {
font-family: var(--font-mono);
font-size: 12px;
line-height: 1.6;
display: flex;
align-items: center;
gap: 4px;
}
.inspector-quickedit-row .inspector-prop-name {
color: var(--zinc-400);
flex-shrink: 0;
}
.inspector-quickedit-value {
color: var(--text-body);
cursor: pointer;
padding: 1px 4px;
border-radius: 2px;
transition: background 150ms;
min-width: 40px;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.inspector-quickedit-value:hover {
background: var(--bg-hover);
}
.inspector-quickedit-input {
font-family: var(--font-mono);
font-size: 12px;
background: var(--bg-base);
border: 1px solid var(--amber-500);
border-radius: 2px;
color: var(--text-heading);
padding: 1px 4px;
outline: none;
width: 100%;
}
/* ─── Send to Agent ──────────────────────────────────── */
.inspector-send {
padding: 8px 12px;
background: var(--bg-surface);
border-top: 1px solid var(--border);
flex-shrink: 0;
position: sticky;
bottom: 0;
}
.inspector-send-btn {
width: 100%;
height: 32px;
background: var(--amber-500);
border: none;
border-radius: var(--radius-md);
color: #000;
font-family: var(--font-system);
font-size: 13px;
font-weight: 600;
cursor: pointer;
transition: all 150ms;
}
.inspector-send-btn:hover {
background: var(--amber-400);
}
.inspector-send-btn:active {
transform: scale(0.98);
}
/* ─── Accessibility ───────────────────────────────────── */
:focus-visible {
outline: 2px solid var(--amber-500);
+93 -2
View File
@@ -14,6 +14,9 @@
</div>
</div>
<!-- Browser tab bar -->
<div class="browser-tabs" id="browser-tabs" style="display:none"></div>
<!-- Chat Tab (default, full height) -->
<main id="tab-chat" class="tab-content active">
<div class="chat-messages" id="chat-messages">
@@ -48,14 +51,101 @@
<div class="refs-footer" id="refs-footer"></div>
</main>
<!-- Debug: Inspector Tab (hidden by default) -->
<main id="tab-inspector" class="tab-content">
<!-- Toolbar: always visible -->
<div class="inspector-toolbar" id="inspector-toolbar">
<button class="inspector-pick-btn" id="inspector-pick-btn" title="Pick an element (click, then click any element on the page)">
<span class="inspector-pick-icon">&#x271B;</span> Pick
</button>
<span class="inspector-selected" id="inspector-selected"></span>
<span class="inspector-mode-badge" id="inspector-mode-badge" style="display:none"></span>
<div style="flex:1"></div>
<button id="inspector-cleanup-btn" class="inspector-action-btn" title="Remove ads, banners, popups">🧹</button>
<button id="inspector-screenshot-btn" class="inspector-action-btn" title="Take a screenshot">📸</button>
</div>
<!-- Inspector content area -->
<div class="inspector-content" id="inspector-content">
<!-- Empty state (before first pick) -->
<div class="inspector-empty" id="inspector-empty">
<div class="inspector-empty-icon">&#x271B;</div>
<p>Pick an element to inspect</p>
<p class="muted">Click the button above, then click any element on the page</p>
</div>
<!-- Loading state -->
<div class="inspector-loading" id="inspector-loading" style="display:none">
<div class="inspector-loading-text">Inspecting...</div>
<div class="inspector-skeleton">
<div class="inspector-skeleton-bar"></div>
<div class="inspector-skeleton-bar"></div>
<div class="inspector-skeleton-bar"></div>
</div>
</div>
<!-- Error state -->
<div class="inspector-error" id="inspector-error" style="display:none"></div>
<!-- Inspector data panels -->
<div class="inspector-panels" id="inspector-panels" style="display:none">
<!-- Box Model -->
<div class="inspector-section" id="inspector-boxmodel-section">
<div class="inspector-section-header">Box Model</div>
<div class="inspector-boxmodel" id="inspector-boxmodel"></div>
</div>
<!-- Matched Rules -->
<div class="inspector-section" id="inspector-rules-section">
<button class="inspector-section-toggle" data-section="rules" aria-expanded="true">
<span class="inspector-toggle-arrow">&#x25BC;</span>
<span>Matched Rules</span>
<span class="inspector-rule-count" id="inspector-rule-count"></span>
</button>
<div class="inspector-section-body" id="inspector-rules" role="tree"></div>
</div>
<!-- Computed Styles -->
<div class="inspector-section" id="inspector-computed-section">
<button class="inspector-section-toggle collapsed" data-section="computed" aria-expanded="false">
<span class="inspector-toggle-arrow">&#x25B6;</span>
<span>Computed</span>
</button>
<div class="inspector-section-body collapsed" id="inspector-computed"></div>
</div>
<!-- Quick Edit -->
<div class="inspector-section" id="inspector-quickedit-section">
<button class="inspector-section-toggle collapsed" data-section="quickedit" aria-expanded="false">
<span class="inspector-toggle-arrow">&#x25B6;</span>
<span>Quick Edit</span>
</button>
<div class="inspector-section-body collapsed" id="inspector-quickedit"></div>
</div>
</div>
</div>
<!-- Send to Agent: sticky bottom -->
<div class="inspector-send" id="inspector-send" style="display:none">
<button class="inspector-send-btn" id="inspector-send-btn">Send to Agent</button>
</div>
</main>
<!-- Experimental chat banner (shown when chatEnabled) -->
<div id="experimental-banner" class="experimental-banner" style="display: none;">
&#x26A0; Standalone mode &mdash; this is a separate agent from your workspace
Browser co-pilot &mdash; controls this browser, reports back to your workspace
</div>
<!-- Quick Actions Toolbar -->
<div class="quick-actions" id="quick-actions">
<button id="chat-cleanup-btn" class="quick-action-btn" title="Remove ads, banners, popups">🧹 Cleanup</button>
<button id="chat-screenshot-btn" class="quick-action-btn" title="Take a screenshot">📸 Screenshot</button>
</div>
<!-- Command Bar -->
<div class="command-bar">
<input type="text" class="command-input" id="command-input" placeholder="Message Claude Code..." autocomplete="off" spellcheck="false">
<button class="stop-btn" id="stop-agent-btn" title="Stop agent" style="display: none;">&#x25A0;</button>
<input type="text" class="command-input" id="command-input" placeholder="Ask about this page..." autocomplete="off" spellcheck="false">
<button class="send-btn" id="send-btn" title="Send">&#x2191;</button>
</div>
@@ -76,6 +166,7 @@
<nav class="tabs debug-tabs" id="debug-tabs" role="tablist" style="display:none">
<button class="tab" role="tab" data-tab="activity">Activity</button>
<button class="tab" role="tab" data-tab="refs">Refs</button>
<button class="tab" role="tab" data-tab="inspector">Inspector</button>
<button class="tab close-debug" id="close-debug" title="Close debug">&times;</button>
</nav>
+832 -6
View File
@@ -17,6 +17,10 @@ let serverToken = null;
let chatLineCount = 0;
let chatPollInterval = null;
let connState = 'disconnected'; // disconnected | connected | reconnecting | dead
let lastOptimisticMsg = null; // track optimistically rendered user msg to avoid dupes
let sidebarActiveTabId = null; // which browser tab's chat we're showing
const chatLineCountByTab = {}; // tabId -> last seen chatLineCount
const chatDomByTab = {}; // tabId -> saved innerHTML
let reconnectAttempts = 0;
let reconnectTimer = null;
const MAX_RECONNECT_ATTEMPTS = 30; // 30 * 2s = 60s before showing "dead"
@@ -98,13 +102,27 @@ let agentContainer = null; // The container for the current agent response
let agentTextEl = null; // The text accumulator element
let agentText = ''; // Accumulated text
// Dedup: track which entry IDs have already been rendered to prevent
// repeat rendering on reconnect or tab switch (server replays from disk)
const renderedEntryIds = new Set();
function addChatEntry(entry) {
// Dedup by entry ID — prevent repeat rendering on reconnect/replay
if (entry.id !== undefined) {
if (renderedEntryIds.has(entry.id)) return;
renderedEntryIds.add(entry.id);
}
// Remove welcome message on first real message
const welcome = chatMessages.querySelector('.chat-welcome');
if (welcome) welcome.remove();
// User messages → chat bubble
// User messages → chat bubble (skip if we already rendered it optimistically)
if (entry.role === 'user') {
if (lastOptimisticMsg === entry.message) {
lastOptimisticMsg = null; // consumed — don't skip next identical msg
return;
}
const bubble = document.createElement('div');
bubble.className = 'chat-bubble user';
bubble.innerHTML = `${escapeHtml(entry.message)}<span class="chat-time">${formatChatTime(entry.ts)}</span>`;
@@ -127,6 +145,16 @@ function addChatEntry(entry) {
return;
}
// System notifications (cleanup, screenshot, errors)
if (entry.type === 'notification') {
const note = document.createElement('div');
note.className = 'chat-notification';
note.textContent = entry.message;
chatMessages.appendChild(note);
note.scrollIntoView({ behavior: 'smooth', block: 'end' });
return;
}
// Agent streaming events
if (entry.role === 'agent') {
handleAgentEvent(entry);
@@ -136,6 +164,13 @@ function addChatEntry(entry) {
function handleAgentEvent(entry) {
if (entry.type === 'agent_start') {
// If we already showed thinking dots optimistically in sendMessage(),
// don't duplicate. Just ensure fast polling is on.
if (agentContainer && document.getElementById('agent-thinking')) {
startFastPoll();
updateStopButton(true);
return;
}
// Create a new agent response container
agentText = '';
agentContainer = document.createElement('div');
@@ -150,6 +185,8 @@ function handleAgentEvent(entry) {
thinking.innerHTML = '<span class="thinking-dot"></span><span class="thinking-dot"></span><span class="thinking-dot"></span>';
agentContainer.appendChild(thinking);
agentContainer.scrollIntoView({ behavior: 'smooth', block: 'end' });
startFastPoll();
updateStopButton(true);
return;
}
@@ -157,6 +194,8 @@ function handleAgentEvent(entry) {
// Remove thinking indicator
const thinking = document.getElementById('agent-thinking');
if (thinking) thinking.remove();
updateStopButton(false);
stopFastPoll();
// Add timestamp
if (agentContainer) {
const ts = document.createElement('span');
@@ -172,6 +211,8 @@ function handleAgentEvent(entry) {
if (entry.type === 'agent_error') {
const thinking = document.getElementById('agent-thinking');
if (thinking) thinking.remove();
updateStopButton(false);
stopFastPoll();
if (!agentContainer) {
agentContainer = document.createElement('div');
agentContainer.className = 'agent-response';
@@ -200,7 +241,11 @@ function handleAgentEvent(entry) {
toolEl.className = 'agent-tool';
const toolName = entry.tool || 'Tool';
const toolInput = entry.input || '';
toolEl.innerHTML = `<span class="tool-name">${escapeHtml(toolName)}</span> <span class="tool-input">${escapeHtml(toolInput)}</span>`;
// Use the verbose description as the primary text
// The tool name becomes a subtle badge
const toolIcon = toolName === 'Bash' ? '▸' : toolName === 'Read' ? '📄' : toolName === 'Grep' ? '🔍' : toolName === 'Glob' ? '📁' : '⚡';
toolEl.innerHTML = `<span class="tool-icon">${toolIcon}</span> <span class="tool-description">${escapeHtml(toolInput)}</span>`;
agentContainer.appendChild(toolEl);
agentContainer.scrollIntoView({ behavior: 'smooth', block: 'end' });
return;
@@ -251,8 +296,34 @@ async function sendMessage() {
commandInput.disabled = true;
sendBtn.disabled = true;
// Show user bubble + thinking dots IMMEDIATELY — don't wait for poll.
// This eliminates up to 1000ms of perceived latency.
lastOptimisticMsg = msg;
const welcome = chatMessages.querySelector('.chat-welcome');
if (welcome) welcome.remove();
const userBubble = document.createElement('div');
userBubble.className = 'chat-bubble user';
userBubble.innerHTML = `${escapeHtml(msg)}<span class="chat-time">${formatChatTime(new Date().toISOString())}</span>`;
chatMessages.appendChild(userBubble);
agentText = '';
agentContainer = document.createElement('div');
agentContainer.className = 'agent-response';
agentTextEl = null;
chatMessages.appendChild(agentContainer);
const thinking = document.createElement('div');
thinking.className = 'agent-thinking';
thinking.id = 'agent-thinking';
thinking.innerHTML = '<span class="thinking-dot"></span><span class="thinking-dot"></span><span class="thinking-dot"></span>';
agentContainer.appendChild(thinking);
agentContainer.scrollIntoView({ behavior: 'smooth', block: 'end' });
updateStopButton(true);
// Speed up polling while agent is working
startFastPoll();
const result = await new Promise((resolve) => {
chrome.runtime.sendMessage({ type: 'sidebar-command', message: msg }, resolve);
chrome.runtime.sendMessage({ type: 'sidebar-command', message: msg, tabId: sidebarActiveTabId }, resolve);
});
commandInput.disabled = false;
@@ -260,7 +331,7 @@ async function sendMessage() {
commandInput.focus();
if (result?.ok) {
// Immediately poll to show the user's own message
// Poll immediately to sync server state
pollChat();
} else {
commandInput.classList.add('error');
@@ -286,6 +357,7 @@ commandInput.addEventListener('keydown', (e) => {
});
sendBtn.addEventListener('click', sendMessage);
document.getElementById('stop-agent-btn').addEventListener('click', stopAgent);
// Poll for new chat messages
let initialLoadDone = false;
@@ -293,16 +365,25 @@ let initialLoadDone = false;
async function pollChat() {
if (!serverUrl || !serverToken) return;
try {
const resp = await fetch(`${serverUrl}/sidebar-chat?after=${chatLineCount}`, {
// Request chat for the currently displayed tab
const tabParam = sidebarActiveTabId !== null ? `&tabId=${sidebarActiveTabId}` : '';
const resp = await fetch(`${serverUrl}/sidebar-chat?after=${chatLineCount}${tabParam}`, {
headers: authHeaders(),
signal: AbortSignal.timeout(3000),
});
if (!resp.ok) return;
const data = await resp.json();
// Detect tab switch from server — swap chat context
if (data.activeTabId !== undefined && data.activeTabId !== sidebarActiveTabId) {
switchChatTab(data.activeTabId);
return; // switchChatTab triggers a fresh poll
}
// First successful poll — hide loading spinner
if (!initialLoadDone) {
initialLoadDone = true;
sidebarActiveTabId = data.activeTabId ?? null;
const loading = document.getElementById('chat-loading');
const welcome = document.getElementById('chat-welcome');
if (loading) loading.style.display = 'none';
@@ -319,6 +400,181 @@ async function pollChat() {
}
chatLineCount = data.total;
}
// Clean up orphaned thinking indicators after replay.
const thinking = document.getElementById('agent-thinking');
if (thinking && data.agentStatus !== 'processing') {
thinking.remove();
if (agentContainer) {
const notice = document.createElement('div');
notice.className = 'agent-text';
notice.style.color = 'var(--text-meta)';
notice.style.fontStyle = 'italic';
notice.textContent = '(session ended)';
agentContainer.appendChild(notice);
agentContainer = null;
agentTextEl = null;
}
}
// Show/hide stop button based on agent status
updateStopButton(data.agentStatus === 'processing');
} catch {}
}
/** Switch the sidebar to show a different tab's chat context */
function switchChatTab(newTabId) {
if (newTabId === sidebarActiveTabId) return;
// Save current tab's chat DOM + scroll position
if (sidebarActiveTabId !== null) {
chatDomByTab[sidebarActiveTabId] = chatMessages.innerHTML;
chatLineCountByTab[sidebarActiveTabId] = chatLineCount;
}
sidebarActiveTabId = newTabId;
// Restore saved chat for new tab, or show welcome
if (chatDomByTab[newTabId]) {
chatMessages.innerHTML = chatDomByTab[newTabId];
chatLineCount = chatLineCountByTab[newTabId] || 0;
} else {
chatMessages.innerHTML = `
<div class="chat-welcome" id="chat-welcome">
<div class="chat-welcome-icon">G</div>
<p>Send a message about this page.</p>
<p class="muted">Each tab has its own conversation.</p>
</div>`;
chatLineCount = 0;
}
// Reset agent state for this tab
agentContainer = null;
agentTextEl = null;
agentText = '';
// Immediately poll the new tab's chat
pollChat();
}
function updateStopButton(agentRunning) {
const stopBtn = document.getElementById('stop-agent-btn');
if (!stopBtn) return;
stopBtn.style.display = agentRunning ? '' : 'none';
}
async function stopAgent() {
if (!serverUrl) return;
try {
await fetch(`${serverUrl}/sidebar-agent/stop`, { method: 'POST', headers: authHeaders() });
} catch {}
// Immediately clean up UI
const thinking = document.getElementById('agent-thinking');
if (thinking) thinking.remove();
if (agentContainer) {
const notice = document.createElement('div');
notice.className = 'agent-text';
notice.style.color = 'var(--text-meta)';
notice.style.fontStyle = 'italic';
notice.textContent = 'Stopped';
agentContainer.appendChild(notice);
agentContainer = null;
agentTextEl = null;
}
updateStopButton(false);
stopFastPoll();
}
// ─── Adaptive poll speed ─────────────────────────────────────────
// 300ms while agent is working (fast first-token), 1000ms when idle.
const FAST_POLL_MS = 300;
const SLOW_POLL_MS = 1000;
function startFastPoll() {
if (chatPollInterval) clearInterval(chatPollInterval);
chatPollInterval = setInterval(pollChat, FAST_POLL_MS);
}
function stopFastPoll() {
if (chatPollInterval) clearInterval(chatPollInterval);
chatPollInterval = setInterval(pollChat, SLOW_POLL_MS);
}
// ─── Browser Tab Bar ─────────────────────────────────────────────
let tabPollInterval = null;
let lastTabJson = '';
async function pollTabs() {
if (!serverUrl || !serverToken) return;
try {
// Tell the server which Chrome tab the user is actually looking at.
// This syncs manual tab switches in the browser → server activeTabId.
let activeTabUrl = null;
try {
const chromeTabs = await chrome.tabs.query({ active: true, currentWindow: true });
activeTabUrl = chromeTabs?.[0]?.url || null;
} catch {}
const resp = await fetch(`${serverUrl}/sidebar-tabs${activeTabUrl ? '?activeUrl=' + encodeURIComponent(activeTabUrl) : ''}`, {
headers: authHeaders(),
signal: AbortSignal.timeout(2000),
});
if (!resp.ok) return;
const data = await resp.json();
if (!data.tabs) return;
// Only re-render if tabs changed
const json = JSON.stringify(data.tabs);
if (json === lastTabJson) return;
lastTabJson = json;
renderTabBar(data.tabs);
} catch {}
}
function renderTabBar(tabs) {
const bar = document.getElementById('browser-tabs');
if (!bar) return;
if (!tabs || tabs.length <= 1) {
bar.style.display = 'none';
return;
}
bar.style.display = '';
bar.innerHTML = '';
for (const tab of tabs) {
const el = document.createElement('div');
el.className = 'browser-tab' + (tab.active ? ' active' : '');
el.title = tab.url || '';
// Show favicon-style domain + title
let label = tab.title || '';
if (!label && tab.url) {
try { label = new URL(tab.url).hostname; } catch { label = tab.url; }
}
if (label.length > 20) label = label.slice(0, 20) + '…';
el.textContent = label || `Tab ${tab.id}`;
el.dataset.tabId = tab.id;
el.addEventListener('click', () => switchBrowserTab(tab.id));
bar.appendChild(el);
}
}
async function switchBrowserTab(tabId) {
if (!serverUrl) return;
try {
await fetch(`${serverUrl}/sidebar-tabs/switch`, {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify({ id: tabId }),
});
// Switch chat context + re-poll tabs
switchChatTab(tabId);
pollTabs();
} catch {}
}
@@ -331,6 +587,7 @@ document.getElementById('clear-chat').addEventListener('click', async () => {
} catch {}
// Reset local state
chatLineCount = 0;
renderedEntryIds.clear();
agentContainer = null;
agentTextEl = null;
agentText = '';
@@ -523,8 +780,537 @@ async function fetchRefs() {
} catch {}
}
// ─── Inspector Tab ──────────────────────────────────────────────
let inspectorPickerActive = false;
let inspectorData = null; // last inspect result
let inspectorModifications = []; // tracked style changes
let inspectorSSE = null;
// Inspector DOM refs
const inspectorPickBtn = document.getElementById('inspector-pick-btn');
const inspectorSelected = document.getElementById('inspector-selected');
const inspectorModeBadge = document.getElementById('inspector-mode-badge');
const inspectorEmpty = document.getElementById('inspector-empty');
const inspectorLoading = document.getElementById('inspector-loading');
const inspectorError = document.getElementById('inspector-error');
const inspectorPanels = document.getElementById('inspector-panels');
const inspectorBoxmodel = document.getElementById('inspector-boxmodel');
const inspectorRules = document.getElementById('inspector-rules');
const inspectorRuleCount = document.getElementById('inspector-rule-count');
const inspectorComputed = document.getElementById('inspector-computed');
const inspectorQuickedit = document.getElementById('inspector-quickedit');
const inspectorSend = document.getElementById('inspector-send');
const inspectorSendBtn = document.getElementById('inspector-send-btn');
// Pick button
inspectorPickBtn.addEventListener('click', () => {
if (inspectorPickerActive) {
inspectorPickerActive = false;
inspectorPickBtn.classList.remove('active');
chrome.runtime.sendMessage({ type: 'stopInspector' });
} else {
inspectorPickerActive = true;
inspectorPickBtn.classList.add('active');
inspectorShowLoading(false); // don't show loading yet, just activate
chrome.runtime.sendMessage({ type: 'startInspector' }, (result) => {
if (result?.error) {
inspectorPickerActive = false;
inspectorPickBtn.classList.remove('active');
inspectorShowError(result.error);
}
});
}
});
function inspectorShowEmpty() {
inspectorEmpty.style.display = '';
inspectorLoading.style.display = 'none';
inspectorError.style.display = 'none';
inspectorPanels.style.display = 'none';
inspectorSend.style.display = 'none';
}
function inspectorShowLoading(show) {
if (show) {
inspectorEmpty.style.display = 'none';
inspectorLoading.style.display = '';
inspectorError.style.display = 'none';
inspectorPanels.style.display = 'none';
} else {
inspectorLoading.style.display = 'none';
}
}
function inspectorShowError(message) {
inspectorEmpty.style.display = 'none';
inspectorLoading.style.display = 'none';
inspectorError.style.display = '';
inspectorError.textContent = message;
inspectorPanels.style.display = 'none';
}
function inspectorShowData(data) {
inspectorData = data;
inspectorModifications = [];
inspectorEmpty.style.display = 'none';
inspectorLoading.style.display = 'none';
inspectorError.style.display = 'none';
inspectorPanels.style.display = '';
inspectorSend.style.display = '';
// Update toolbar
const tag = data.tagName || '?';
const cls = data.classes && data.classes.length > 0 ? '.' + data.classes.join('.') : '';
const idStr = data.id ? '#' + data.id : '';
inspectorSelected.textContent = `<${tag}>${idStr}${cls}`;
inspectorSelected.title = data.selector;
// Mode badge
if (data.mode === 'basic') {
inspectorModeBadge.textContent = 'Basic mode';
inspectorModeBadge.style.display = '';
inspectorModeBadge.className = 'inspector-mode-badge basic';
} else if (data.mode === 'cdp') {
inspectorModeBadge.textContent = 'CDP';
inspectorModeBadge.style.display = '';
inspectorModeBadge.className = 'inspector-mode-badge cdp';
} else {
inspectorModeBadge.style.display = 'none';
}
// Render sections
renderBoxModel(data);
renderMatchedRules(data);
renderComputedStyles(data);
renderQuickEdit(data);
updateSendButton();
}
// ─── Box Model Rendering ────────────────────────────────────────
function renderBoxModel(data) {
const box = data.basicData?.boxModel || data.boxModel;
if (!box) { inspectorBoxmodel.innerHTML = '<span class="inspector-no-data">No box model data</span>'; return; }
const m = box.margin || {};
const b = box.border || {};
const p = box.padding || {};
const c = box.content || {};
inspectorBoxmodel.innerHTML = `
<div class="boxmodel-margin">
<span class="boxmodel-label">margin</span>
<span class="boxmodel-value boxmodel-top">${fmtBoxVal(m.top)}</span>
<span class="boxmodel-value boxmodel-right">${fmtBoxVal(m.right)}</span>
<span class="boxmodel-value boxmodel-bottom">${fmtBoxVal(m.bottom)}</span>
<span class="boxmodel-value boxmodel-left">${fmtBoxVal(m.left)}</span>
<div class="boxmodel-border">
<span class="boxmodel-label">border</span>
<span class="boxmodel-value boxmodel-top">${fmtBoxVal(b.top)}</span>
<span class="boxmodel-value boxmodel-right">${fmtBoxVal(b.right)}</span>
<span class="boxmodel-value boxmodel-bottom">${fmtBoxVal(b.bottom)}</span>
<span class="boxmodel-value boxmodel-left">${fmtBoxVal(b.left)}</span>
<div class="boxmodel-padding">
<span class="boxmodel-label">padding</span>
<span class="boxmodel-value boxmodel-top">${fmtBoxVal(p.top)}</span>
<span class="boxmodel-value boxmodel-right">${fmtBoxVal(p.right)}</span>
<span class="boxmodel-value boxmodel-bottom">${fmtBoxVal(p.bottom)}</span>
<span class="boxmodel-value boxmodel-left">${fmtBoxVal(p.left)}</span>
<div class="boxmodel-content">
<span>${Math.round(c.width || 0)} x ${Math.round(c.height || 0)}</span>
</div>
</div>
</div>
</div>
`;
}
function fmtBoxVal(v) {
if (v === undefined || v === null) return '-';
const n = typeof v === 'number' ? v : parseFloat(v);
if (isNaN(n) || n === 0) return '0';
return Math.round(n * 10) / 10;
}
// ─── Matched Rules Rendering ────────────────────────────────────
function renderMatchedRules(data) {
const rules = data.matchedRules || data.basicData?.matchedRules || [];
inspectorRuleCount.textContent = rules.length > 0 ? `(${rules.length})` : '';
if (rules.length === 0) {
inspectorRules.innerHTML = '<div class="inspector-no-data">No matched rules</div>';
return;
}
// Separate UA rules from author rules
const authorRules = [];
const uaRules = [];
for (const rule of rules) {
if (rule.origin === 'user-agent' || rule.isUA) {
uaRules.push(rule);
} else {
authorRules.push(rule);
}
}
let html = '';
// Author rules (expanded)
for (const rule of authorRules) {
html += renderRule(rule, false);
}
// UA rules (collapsed by default)
if (uaRules.length > 0) {
html += `
<div class="inspector-ua-rules">
<button class="inspector-ua-toggle collapsed" aria-expanded="false">
<span class="inspector-toggle-arrow">&#x25B6;</span>
User Agent (${uaRules.length})
</button>
<div class="inspector-ua-body collapsed">
`;
for (const rule of uaRules) {
html += renderRule(rule, true);
}
html += '</div></div>';
}
inspectorRules.innerHTML = html;
// Bind UA toggle
const uaToggle = inspectorRules.querySelector('.inspector-ua-toggle');
if (uaToggle) {
uaToggle.addEventListener('click', () => {
const body = inspectorRules.querySelector('.inspector-ua-body');
const isCollapsed = uaToggle.classList.contains('collapsed');
uaToggle.classList.toggle('collapsed', !isCollapsed);
uaToggle.setAttribute('aria-expanded', isCollapsed);
uaToggle.querySelector('.inspector-toggle-arrow').innerHTML = isCollapsed ? '&#x25BC;' : '&#x25B6;';
body.classList.toggle('collapsed', !isCollapsed);
});
}
}
function renderRule(rule, isUA) {
const selectorText = escapeHtml(rule.selector || '');
const truncatedSelector = selectorText.length > 35 ? selectorText.slice(0, 35) + '...' : selectorText;
const source = rule.source || '';
const sourceDisplay = source.includes('/') ? source.split('/').pop() : source;
const specificity = rule.specificity || '';
let propsHtml = '';
const props = rule.properties || [];
for (const prop of props) {
const overridden = prop.overridden ? ' overridden' : '';
const nameHtml = escapeHtml(prop.name);
const valText = escapeHtml(prop.value || '');
const truncatedVal = valText.length > 30 ? valText.slice(0, 30) + '...' : valText;
const priority = prop.priority === 'important' ? ' <span class="inspector-important">!important</span>' : '';
propsHtml += `<div class="inspector-prop${overridden}"><span class="inspector-prop-name">${nameHtml}</span>: <span class="inspector-prop-value" title="${valText}">${truncatedVal}</span>${priority};</div>`;
}
return `
<div class="inspector-rule" role="treeitem">
<div class="inspector-rule-header">
<span class="inspector-selector" title="${selectorText}">${truncatedSelector}</span>
${specificity ? `<span class="inspector-specificity">${escapeHtml(specificity)}</span>` : ''}
</div>
<div class="inspector-rule-props">${propsHtml}</div>
${sourceDisplay ? `<div class="inspector-rule-source">${escapeHtml(sourceDisplay)}</div>` : ''}
</div>
`;
}
// ─── Computed Styles Rendering ──────────────────────────────────
function renderComputedStyles(data) {
const styles = data.computedStyles || data.basicData?.computedStyles || {};
const keys = Object.keys(styles);
if (keys.length === 0) {
inspectorComputed.innerHTML = '<div class="inspector-no-data">No computed styles</div>';
return;
}
let html = '';
for (const key of keys) {
const val = styles[key];
if (!val || val === 'none' || val === 'normal' || val === 'auto' || val === '0px' || val === 'rgba(0, 0, 0, 0)') continue;
html += `<div class="inspector-computed-row"><span class="inspector-prop-name">${escapeHtml(key)}</span>: <span class="inspector-prop-value">${escapeHtml(val)}</span></div>`;
}
if (!html) {
html = '<div class="inspector-no-data">All values are defaults</div>';
}
inspectorComputed.innerHTML = html;
}
// ─── Quick Edit ─────────────────────────────────────────────────
function renderQuickEdit(data) {
const selector = data.selector;
if (!selector) { inspectorQuickedit.innerHTML = ''; return; }
// Show common editable properties with current values
const editableProps = ['color', 'background-color', 'font-size', 'padding', 'margin', 'border', 'display', 'opacity'];
const computed = data.computedStyles || data.basicData?.computedStyles || {};
let html = '<div class="inspector-quickedit-list">';
for (const prop of editableProps) {
const val = computed[prop] || '';
html += `
<div class="inspector-quickedit-row" data-prop="${escapeHtml(prop)}">
<span class="inspector-prop-name">${escapeHtml(prop)}</span>:
<span class="inspector-quickedit-value" data-selector="${escapeHtml(selector)}" data-prop="${escapeHtml(prop)}" tabindex="0" role="button" title="Click to edit">${escapeHtml(val || '(none)')}</span>
</div>
`;
}
html += '</div>';
inspectorQuickedit.innerHTML = html;
// Bind click-to-edit
inspectorQuickedit.querySelectorAll('.inspector-quickedit-value').forEach(el => {
el.addEventListener('click', () => startQuickEdit(el));
el.addEventListener('keydown', (e) => {
if (e.key === 'Enter' || e.key === ' ') { e.preventDefault(); startQuickEdit(el); }
});
});
}
function startQuickEdit(valueEl) {
if (valueEl.querySelector('input')) return; // already editing
const currentVal = valueEl.textContent === '(none)' ? '' : valueEl.textContent;
const prop = valueEl.dataset.prop;
const selector = valueEl.dataset.selector;
const input = document.createElement('input');
input.type = 'text';
input.className = 'inspector-quickedit-input';
input.value = currentVal;
valueEl.textContent = '';
valueEl.appendChild(input);
input.focus();
input.select();
function commit() {
const newVal = input.value.trim();
valueEl.textContent = newVal || '(none)';
if (newVal && newVal !== currentVal) {
chrome.runtime.sendMessage({
type: 'applyStyle',
selector,
property: prop,
value: newVal,
});
inspectorModifications.push({ property: prop, value: newVal, selector });
updateSendButton();
}
}
function cancel() {
valueEl.textContent = currentVal || '(none)';
}
input.addEventListener('blur', commit);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') { e.preventDefault(); input.blur(); }
if (e.key === 'Escape') { e.preventDefault(); input.removeEventListener('blur', commit); cancel(); }
});
}
// ─── Send to Agent ──────────────────────────────────────────────
function updateSendButton() {
if (inspectorModifications.length > 0) {
inspectorSendBtn.textContent = 'Send to Code';
inspectorSendBtn.title = `${inspectorModifications.length} modification(s) to send`;
} else {
inspectorSendBtn.textContent = 'Send to Agent';
inspectorSendBtn.title = 'Send full inspector data';
}
}
inspectorSendBtn.addEventListener('click', () => {
if (!inspectorData) return;
let message;
if (inspectorModifications.length > 0) {
// Format modification diff
const diffs = inspectorModifications.map(m =>
` ${m.property}: ${m.value} (selector: ${m.selector})`
).join('\n');
message = `CSS Inspector modifications:\n\nSelector: ${inspectorData.selector}\n\nChanges:\n${diffs}`;
// Include source file info if available
const rules = inspectorData.matchedRules || inspectorData.basicData?.matchedRules || [];
const sources = rules.filter(r => r.source && r.source !== 'inline').map(r => r.source);
if (sources.length > 0) {
message += `\n\nSource files:\n${[...new Set(sources)].map(s => ` ${s}`).join('\n')}`;
}
} else {
// Send full inspector data
message = `CSS Inspector data for: ${inspectorData.selector}\n\n${JSON.stringify(inspectorData, null, 2)}`;
}
chrome.runtime.sendMessage({ type: 'sidebar-command', message });
});
// ─── Quick Action Helpers (shared between chat toolbar + inspector) ──
async function runCleanup(...buttons) {
if (!serverUrl || !serverToken) {
return;
}
buttons.forEach(b => b?.classList.add('loading'));
// Smart cleanup: send a chat message to the sidebar agent (an LLM).
// The agent snapshots the page, understands it semantically, and removes
// clutter intelligently. Much better than brittle CSS selectors.
const cleanupPrompt = [
'Clean up this page for reading. First run a quick deterministic pass:',
'$B cleanup --all',
'',
'Then take a snapshot to see what\'s left:',
'$B snapshot -i',
'',
'Look at the snapshot and identify remaining non-content elements:',
'- Ad placeholders, "ADVERTISEMENT" labels, sponsored content',
'- Cookie/consent banners, newsletter popups, login walls',
'- Audio/podcast player widgets, video autoplay',
'- Sidebar widgets (puzzles, games, "most popular", recommendations)',
'- Social share buttons, follow prompts, "See more on Google"',
'- Floating chat widgets, feedback buttons',
'- Navigation drawers, mega-menus (unless they ARE the page content)',
'- Empty whitespace from removed ads',
'',
'KEEP: the site header/masthead/logo, article headline, article body,',
'article images, author byline, date. The page should still look like',
'the site it is, just without the crap.',
'',
'For each element to remove, run JavaScript via $B to hide it:',
'$B eval "document.querySelector(\'SELECTOR\').style.display=\'none\'"',
'',
'Also unlock scrolling if the page is scroll-locked:',
'$B eval "document.body.style.overflow=\'auto\';document.documentElement.style.overflow=\'auto\'"',
].join('\n');
try {
// Send as a sidebar command (spawns the agent)
const resp = await fetch(`${serverUrl}/sidebar-command`, {
method: 'POST',
headers: authHeaders(),
body: JSON.stringify({ message: cleanupPrompt }),
signal: AbortSignal.timeout(5000),
});
if (resp.ok) {
addChatEntry({ type: 'notification', message: 'Cleaning up page (agent is analyzing...)' });
} else {
addChatEntry({ type: 'notification', message: 'Failed to start cleanup' });
}
} catch (err) {
addChatEntry({ type: 'notification', message: 'Cleanup failed: ' + err.message });
} finally {
// Remove loading after a short delay (agent runs async)
setTimeout(() => buttons.forEach(b => b?.classList.remove('loading')), 2000);
}
}
async function runScreenshot(...buttons) {
if (!serverUrl || !serverToken) {
return;
}
buttons.forEach(b => b?.classList.add('loading'));
try {
const resp = await fetch(`${serverUrl}/command`, {
method: 'POST',
headers: { ...authHeaders(), 'Content-Type': 'application/json' },
body: JSON.stringify({ command: 'screenshot', args: [] }),
signal: AbortSignal.timeout(15000),
});
const text = await resp.text();
if (resp.ok) {
addChatEntry({ type: 'notification', message: text || 'Screenshot saved' });
} else {
const err = JSON.parse(text).error || 'Screenshot failed';
addChatEntry({ type: 'notification', message: 'Error: ' + err });
}
} catch (err) {
addChatEntry({ type: 'notification', message: 'Screenshot failed: ' + err.message });
} finally {
buttons.forEach(b => b?.classList.remove('loading'));
}
}
// ─── Wire up all cleanup/screenshot buttons (inspector + chat toolbar) ──
const inspectorCleanupBtn = document.getElementById('inspector-cleanup-btn');
const inspectorScreenshotBtn = document.getElementById('inspector-screenshot-btn');
const chatCleanupBtn = document.getElementById('chat-cleanup-btn');
const chatScreenshotBtn = document.getElementById('chat-screenshot-btn');
if (inspectorCleanupBtn) inspectorCleanupBtn.addEventListener('click', () => runCleanup(inspectorCleanupBtn, chatCleanupBtn));
if (inspectorScreenshotBtn) inspectorScreenshotBtn.addEventListener('click', () => runScreenshot(inspectorScreenshotBtn, chatScreenshotBtn));
if (chatCleanupBtn) chatCleanupBtn.addEventListener('click', () => runCleanup(chatCleanupBtn, inspectorCleanupBtn));
if (chatScreenshotBtn) chatScreenshotBtn.addEventListener('click', () => runScreenshot(chatScreenshotBtn, inspectorScreenshotBtn));
// ─── Section Toggles ────────────────────────────────────────────
document.querySelectorAll('.inspector-section-toggle').forEach(toggle => {
toggle.addEventListener('click', () => {
const section = toggle.dataset.section;
const body = document.getElementById(`inspector-${section}`);
const isCollapsed = toggle.classList.contains('collapsed');
toggle.classList.toggle('collapsed', !isCollapsed);
toggle.setAttribute('aria-expanded', isCollapsed);
toggle.querySelector('.inspector-toggle-arrow').innerHTML = isCollapsed ? '&#x25BC;' : '&#x25B6;';
body.classList.toggle('collapsed', !isCollapsed);
});
});
// ─── Inspector SSE ──────────────────────────────────────────────
function connectInspectorSSE() {
if (!serverUrl || !serverToken) return;
if (inspectorSSE) { inspectorSSE.close(); inspectorSSE = null; }
const tokenParam = serverToken ? `&token=${serverToken}` : '';
const url = `${serverUrl}/inspector/events?_=${Date.now()}${tokenParam}`;
try {
inspectorSSE = new EventSource(url);
inspectorSSE.addEventListener('inspectResult', (e) => {
try {
const data = JSON.parse(e.data);
inspectorShowData(data);
} catch {}
});
inspectorSSE.addEventListener('error', () => {
// SSE connection failed — inspector works without it (basic mode)
if (inspectorSSE) { inspectorSSE.close(); inspectorSSE = null; }
});
} catch {
// SSE not available — that's fine
}
}
// ─── Server Discovery ───────────────────────────────────────────
function setActionButtonsEnabled(enabled) {
const btns = document.querySelectorAll('.quick-action-btn, .inspector-action-btn');
btns.forEach(btn => {
btn.disabled = !enabled;
btn.classList.toggle('disabled', !enabled);
});
}
function updateConnection(url, token) {
const wasConnected = !!serverUrl;
serverUrl = url;
@@ -534,14 +1320,22 @@ function updateConnection(url, token) {
const port = new URL(url).port;
document.getElementById('footer-port').textContent = `:${port}`;
setConnState('connected');
setActionButtonsEnabled(true);
connectSSE();
connectInspectorSSE();
if (chatPollInterval) clearInterval(chatPollInterval);
chatPollInterval = setInterval(pollChat, 1000);
chatPollInterval = setInterval(pollChat, SLOW_POLL_MS);
pollChat();
// Poll browser tabs every 2s (lightweight, just tab list)
if (tabPollInterval) clearInterval(tabPollInterval);
tabPollInterval = setInterval(pollTabs, 2000);
pollTabs();
} else {
document.getElementById('footer-dot').className = 'dot';
document.getElementById('footer-port').textContent = '';
setActionButtonsEnabled(false);
if (chatPollInterval) { clearInterval(chatPollInterval); chatPollInterval = null; }
if (tabPollInterval) { clearInterval(tabPollInterval); tabPollInterval = null; }
if (wasConnected) {
startReconnect();
}
@@ -623,6 +1417,38 @@ chrome.runtime.onMessage.addListener((msg) => {
fetchRefs();
}
}
if (msg.type === 'inspectResult') {
inspectorPickerActive = false;
inspectorPickBtn.classList.remove('active');
if (msg.data) {
inspectorShowData(msg.data);
} else {
inspectorShowError('Element not found, try picking again');
}
}
if (msg.type === 'pickerCancelled') {
inspectorPickerActive = false;
inspectorPickBtn.classList.remove('active');
}
// Instant tab switch — background.js fires this on chrome.tabs.onActivated
if (msg.type === 'browserTabActivated') {
// Tell the server which tab is now active, then switch chat context
if (serverUrl && serverToken) {
fetch(`${serverUrl}/sidebar-tabs?activeUrl=${encodeURIComponent(msg.url || '')}`, {
headers: authHeaders(),
signal: AbortSignal.timeout(2000),
}).then(r => r.json()).then(data => {
if (data.tabs) {
renderTabBar(data.tabs);
// Find the server-side tab ID for this Chrome tab
const activeTab = data.tabs.find(t => t.active);
if (activeTab && activeTab.id !== sidebarActiveTabId) {
switchChatTab(activeTab.id);
}
}
}).catch(() => {});
}
}
});
// ─── Chat Gate ──────────────────────────────────────────────────