Repository navigation
fix(browser): inject scripts from popup capture - #2348
Conversation
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
📝 WalkthroughWalkthroughThe popup script gains two new helpers— ChangesLazy Content Script Injection and Retry
Estimated code review effort🎯 2 (Simple) | ⏱️ ~10 minutes Poem
🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
💡 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".
There was a problem hiding this comment.
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
📒 Files selected for processing (2)
browser-extension/src/popup.jsbrowser-extension/tests/popup.test.js
| 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; |
There was a problem hiding this comment.
🩺 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.
| 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.
| 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) | ||
| })); | ||
| } |
There was a problem hiding this comment.
🎯 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.
| 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 }), | ||
| }), | ||
| ); | ||
| }); |
There was a problem hiding this comment.
📐 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.
|
Historical Codex triage: evidence checked at 5ebcfe5. This records that source revision; it does not claim a fresh review of current master.
Only the rows listed above are dispositioned. Held findings remain open. |
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.capturePagelistener. 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 injectssrc/common.jsplus the provider content script withchrome.scripting.executeScript, then retries the normal capture message. Unsupported pages still report the existing unsupported-page state.Verification
npm --prefix browser-extension test -- --runpassed: 58 tests.npm --prefix browser-extension run lintpassed.npm --prefix browser-extension run validate && npm --prefix browser-extension run buildpassed.devtools verify --quickpassed with run id20260624T011435Z-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.sendMessageAPIs from the extension page; this patch moves that path into the visible popup capture action.Summary by CodeRabbit
Release Notes
New Features
Bug Fixes
Tests