Skip to content

fix(browser): inject scripts from popup capture - #2348

Merged
Sinity merged 1 commit into
masterfrom
feature/fix/browser-popup-inject-capture
Jun 24, 2026
Merged

Sinity merged 1 commit into
masterfrom
feature/fix/browser-popup-inject-capture

Conversation

@Sinity

@Sinity Sinity commented Jun 24, 2026 •

Copy link
Copy Markdown
Owner

Summary

Makes the browser extension popup recover when a supported ChatGPT or Claude tab was already open before the extension content scripts were present.

Problem

The live-extension proof showed that the extension/background/receiver/archive path works, but already-open tabs may not have the polylogue.capturePage listener. The previous workaround was to inject scripts through DevTools before sending the message. That should be normal popup behavior, not an operator workaround.

Solution

The popup now maps supported ChatGPT and Claude hosts to the extension content scripts. When the first chrome.tabs.sendMessage(... polylogue.capturePage ...) attempt fails, it injects src/common.js plus the provider content script with chrome.scripting.executeScript, then retries the normal capture message. Unsupported pages still report the existing unsupported-page state.

Verification

  • npm --prefix browser-extension test -- --run passed: 58 tests.
  • npm --prefix browser-extension run lint passed.
  • npm --prefix browser-extension run validate && npm --prefix browser-extension run build passed.
  • devtools verify --quick passed with run id 20260624T011435Z-quick-1280425-77be9e42.

Live context: before this patch, the extension was loaded into live Chrome and proved against ChatGPT using the same chrome.scripting.executeScript + chrome.tabs.sendMessage APIs from the extension page; this patch moves that path into the visible popup capture action.

Summary by CodeRabbit

Release Notes

  • New Features

    • Improved page capture compatibility and reliability on supported platforms.
  • Bug Fixes

    • Enhanced capture mechanism with automatic script injection and retry logic to handle initial connection failures.
  • Tests

    • Added test coverage for the popup's capture functionality, including script injection and retry scenarios.

Problem: live Chrome tabs opened before the unpacked extension was loaded did not have the content-script listener, so the popup capture action could fail even though the extension, receiver, and archive path were healthy.

What changed: the popup now maps supported ChatGPT and Claude hosts to the extension content scripts, injects them via chrome.scripting.executeScript when the first capture message fails, and retries the normal polylogue.capturePage message. A popup regression test covers the retry path.

Verification: npm --prefix browser-extension test -- --run; npm --prefix browser-extension run lint; npm --prefix browser-extension run validate && npm --prefix browser-extension run build
@coderabbitai

coderabbitai Bot commented Jun 24, 2026 •

Copy link
Copy Markdown

Review Change Stack

📝 Walkthrough

Walkthrough

The popup script gains two new helpers—contentScriptFiles(url) and ensureCaptureScripts(tab)—that select and inject provider-specific content scripts for ChatGPT and Claude tabs. The capture button handler now catches an initial send failure, injects the scripts, and retries once. A new Vitest test suite validates this retry behavior with a mocked Chrome API.

Changes

Lazy Content Script Injection and Retry

Layer / File(s) Summary
Script selection, injection, and capture retry logic
browser-extension/src/popup.js
Adds contentScriptFiles(url) to map ChatGPT/Claude hostnames to script lists, ensureCaptureScripts(tab) to inject them via chrome.scripting.executeScript, and updates the capture handler to catch the first polylogue.capturePage failure, call ensureCaptureScripts, and retry before falling through to the existing offline/unsupported path.
Vitest test suite for capture retry
browser-extension/tests/popup.test.js
Adds a test that mounts a synthetic DOM, installs a stateful Chrome API mock (throwing on the first tabs.sendMessage, succeeding on the second), loads the popup module, clicks capture, and asserts executeScript is called twice with src/common.js and src/content/chatgpt.js while storage.local.set is not called with online: false.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Poem

🐇 When the script's not there, don't give up hope,
Inject it fresh and widen the scope!
A retry, a bounce, a second go-round,
The capture succeeds and the message is found.
No "offline" today — we hopped past the frown! 🌟

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title 'fix(browser): inject scripts from popup capture' directly describes the main change—implementing script injection in the popup's capture functionality—which aligns with the core modification to browser-extension/src/popup.js.
Description check ✅ Passed The description includes all required sections (Summary, Problem, Solution, Verification) and covers the motivation, implementation approach, and validation steps comprehensively.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fix/browser-popup-inject-capture

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 687b9bef02

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread browser-extension/src/popup.js Resolved

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@browser-extension/src/popup.js`:
- Around line 100-109: The current retry logic at the `!result?.ok` guard treats
all false responses the same, including valid content-script replies of `{ ok:
false }`. Instead of checking result status to decide whether to retry, track
whether the first chrome.tabs.sendMessage call actually threw an error. Create a
separate variable to record if an error was thrown during the first message
attempt (when the catch handler is triggered), then only proceed with
ensureCaptureScripts and retry if that variable indicates the message actually
failed to reach a receiver, not just when the response indicates ok is false.
- Around line 29-35: The executeScript call on line 33 within the
ensureCaptureScripts function can reject and throw an error, which currently
bubbles up and breaks the intended boolean control flow of the function. Wrap
the for loop that iterates through files and executes
chrome.scripting.executeScript in a try-catch block. If an exception is caught
during script execution, return false to maintain the boolean contract and allow
the caller's existing failure handling to continue properly.

In `@browser-extension/tests/popup.test.js`:
- Around line 74-94: Add a new test case after the existing "injects provider
content scripts before retrying an already-open tab capture" test that verifies
the behavior when the first tabs.sendMessage call resolves with a logical
failure response (ok: false) rather than throwing an error. In this test, setup
the mock to return { ok: false } on the first sendMessage call, click the
capture button, and then assert that chrome.scripting.executeScript is NOT
called, ensuring that the script injection and retry logic only occurs for
transport/listener errors and not for successful message responses indicating
logical failures.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: ASSERTIVE

Plan: Pro

Run ID: c16a2d4d-61e4-4065-bd5b-f09b9b55e659

📥 Commits

Reviewing files that changed from the base of the PR and between 5327c12 and 687b9be.

📒 Files selected for processing (2)
  • browser-extension/src/popup.js
  • browser-extension/tests/popup.test.js

Comment on lines +29 to +35
async function ensureCaptureScripts(tab) {
const files = contentScriptFiles(tab?.url || "");
if (!tab?.id || !files.length) return false;
for (const file of files) {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: [file] });
}
return true;

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🩺 Stability & Availability | 🟠 Major | ⚡ Quick win

Handle executeScript failures inside the boolean helper.

Line 33 can reject; right now that bubbles out of ensureCaptureScripts and breaks the intended true/false control flow. Catch and return false so capture can continue into existing failure handling.

Suggested fix
 async function ensureCaptureScripts(tab) {
   const files = contentScriptFiles(tab?.url || "");
-  if (!tab?.id || !files.length) return false;
-  for (const file of files) {
-    await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: [file] });
-  }
-  return true;
+  if (tab?.id == null || !files.length) return false;
+  try {
+    for (const file of files) {
+      await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: [file] });
+    }
+    return true;
+  } catch {
+    return false;
+  }
 }
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
async function ensureCaptureScripts(tab) {
const files = contentScriptFiles(tab?.url || "");
if (!tab?.id || !files.length) return false;
for (const file of files) {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: [file] });
}
return true;
async function ensureCaptureScripts(tab) {
const files = contentScriptFiles(tab?.url || "");
if (tab?.id == null || !files.length) return false;
try {
for (const file of files) {
await chrome.scripting.executeScript({ target: { tabId: tab.id }, files: [file] });
}
return true;
} catch {
return false;
}
}
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@browser-extension/src/popup.js` around lines 29 - 35, The executeScript call
on line 33 within the ensureCaptureScripts function can reject and throw an
error, which currently bubbles up and breaks the intended boolean control flow
of the function. Wrap the for loop that iterates through files and executes
chrome.scripting.executeScript in a try-catch block. If an exception is caught
during script execution, return false to maintain the boolean contract and allow
the caller's existing failure handling to continue properly.

Comment on lines +100 to +109
let result = await chrome.tabs.sendMessage(tab.id, { type: "polylogue.capturePage" }).catch((error) => ({
ok: false,
error: String(error.message || error)
}));
if (!result?.ok && (await ensureCaptureScripts(tab))) {
result = await chrome.tabs.sendMessage(tab.id, { type: "polylogue.capturePage" }).catch((error) => ({
ok: false,
error: String(error.message || error)
}));
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Retry injection only when the first message failed to reach a receiver.

The guard at Line 104 uses !result?.ok, which also matches valid content-script replies like { ok: false }. That causes unnecessary reinjection/retry on non-transport failures. Track whether the first sendMessage threw, and only inject/retry in that case.

Suggested fix
-  let result = await chrome.tabs.sendMessage(tab.id, { type: "polylogue.capturePage" }).catch((error) => ({
-    ok: false,
-    error: String(error.message || error)
-  }));
-  if (!result?.ok && (await ensureCaptureScripts(tab))) {
+  let firstSendThrew = false;
+  let result = await chrome.tabs.sendMessage(tab.id, { type: "polylogue.capturePage" }).catch((error) => {
+    firstSendThrew = true;
+    return {
+      ok: false,
+      error: String(error.message || error)
+    };
+  });
+  if (firstSendThrew && (await ensureCaptureScripts(tab))) {
     result = await chrome.tabs.sendMessage(tab.id, { type: "polylogue.capturePage" }).catch((error) => ({
       ok: false,
       error: String(error.message || error)
     }));
   }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@browser-extension/src/popup.js` around lines 100 - 109, The current retry
logic at the `!result?.ok` guard treats all false responses the same, including
valid content-script replies of `{ ok: false }`. Instead of checking result
status to decide whether to retry, track whether the first
chrome.tabs.sendMessage call actually threw an error. Create a separate variable
to record if an error was thrown during the first message attempt (when the
catch handler is triggered), then only proceed with ensureCaptureScripts and
retry if that variable indicates the message actually failed to reach a
receiver, not just when the response indicates ok is false.

Comment on lines +74 to +94
it("injects provider content scripts before retrying an already-open tab capture", async () => {
await loadPopup();

globalThis.document.getElementById("capture").click();

await vi.waitFor(() => expect(globalThis.chrome.tabs.sendMessage).toHaveBeenCalledTimes(2));
expect(globalThis.chrome.scripting.executeScript).toHaveBeenCalledTimes(2);
expect(globalThis.chrome.scripting.executeScript).toHaveBeenNthCalledWith(1, {
target: { tabId: CHATGPT_TAB.id },
files: ["src/common.js"],
});
expect(globalThis.chrome.scripting.executeScript).toHaveBeenNthCalledWith(2, {
target: { tabId: CHATGPT_TAB.id },
files: ["src/content/chatgpt.js"],
});
expect(globalThis.chrome.storage.local.set).not.toHaveBeenCalledWith(
expect.objectContaining({
polylogueState: expect.objectContaining({ online: false }),
}),
);
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Add a regression test for non-transport capture failures.

Please add a case where the first tabs.sendMessage resolves with { ok: false } (no throw) and assert chrome.scripting.executeScript is not called. This locks the retry behavior to missing-listener failures only.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@browser-extension/tests/popup.test.js` around lines 74 - 94, Add a new test
case after the existing "injects provider content scripts before retrying an
already-open tab capture" test that verifies the behavior when the first
tabs.sendMessage call resolves with a logical failure response (ok: false)
rather than throwing an error. In this test, setup the mock to return { ok:
false } on the first sendMessage call, click the capture button, and then assert
that chrome.scripting.executeScript is NOT called, ensuring that the script
injection and retry logic only occurs for transport/listener errors and not for
successful message responses indicating logical failures.

@Sinity
Sinity merged commit 02779ca into master Jun 24, 2026
13 of 14 checks passed
@Sinity
Sinity deleted the feature/fix/browser-popup-inject-capture branch June 24, 2026 01:20
@github-actions github-actions Bot mentioned this pull request Jul 5, 2026
@Sinity

Sinity commented Oct 1, 2026

Copy link
Copy Markdown
Owner Author

Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.

  • 53.F022 / P2: fixed-already at the checked revision: browser-extension/src/content/chatgpt.js:2 and browser-extension/src/content/claude.js:2 return immediately when their capture listener is already installed. Reinjecting after a failed capture therefore cannot install the duplicate provider listeners and mutation observers described in this finding.

Only the rows listed above are dispositioned. Held findings remain open.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant