Skip to content

Commit 57d37ba

Browse files
committed
fix(commands): observe tabs.query/sendMessage promises in genPrompt path
Mirror the pattern already applied in menus.mjs to the keyboard-command genPrompt branch in commands.mjs so no step here can surface as an unhandled promise rejection in the background script: - Browser.tabs.query() is wrapped in try/catch (it can reject on permission errors, etc.). - The resulting tabs[0] is guarded before dereferencing currentTab.id — contextMenus / commands handlers can fire when no active tab is resolvable, matching the guard menus.mjs already added. - Browser.tabs.sendMessage() now has a .catch() that logs and swallows the rejection. webextension-polyfill sendMessage rejects in normal extension usage when no content script is listening, when the page is restricted (chrome://, about:, etc.), or when the content script is stale after an extension reload. Same rationale as commit c8bfcf3 for menus.mjs — addresses the Copilot review on src/background/commands.mjs:33 (PR #963). Lint, prettier, and the test suite (315 tests) all pass. Co-Authored-By: Octopus <liyuan851277048@icloud.com>
1 parent c8bfcf3 commit 57d37ba

1 file changed

Lines changed: 30 additions & 5 deletions

File tree

src/background/commands.mjs

Lines changed: 30 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,36 @@ export function registerCommands() {
3434
}
3535

3636
if (menuConfig[command].genPrompt) {
37-
const currentTab = (await Browser.tabs.query({ active: true, currentWindow: true }))[0]
38-
Browser.tabs.sendMessage(currentTab.id, {
39-
type: 'CREATE_CHAT',
40-
data: message,
41-
})
37+
// Mirror the pattern in menus.mjs so no step here can leak an
38+
// unhandled rejection in the background:
39+
// - Browser.tabs.query() can reject (permission errors, etc.) —
40+
// observe via try/catch.
41+
// - tabs[0] may be undefined when no active tab exists — guard
42+
// before dereferencing currentTab.id.
43+
// - Browser.tabs.sendMessage() (via webextension-polyfill) rejects
44+
// in normal extension usage (no content script listening,
45+
// restricted pages like chrome://, stale content scripts after
46+
// extension reload) — attach a .catch().
47+
let tabs
48+
try {
49+
tabs = await Browser.tabs.query({ active: true, currentWindow: true })
50+
} catch (error) {
51+
console.error(`failed to query active tab for command "${command}"`, error)
52+
return
53+
}
54+
const currentTab = tabs && tabs[0]
55+
if (!currentTab) {
56+
console.debug(`command "${command}" triggered but no active tab found, skipping`)
57+
return
58+
}
59+
Browser.tabs
60+
.sendMessage(currentTab.id, {
61+
type: 'CREATE_CHAT',
62+
data: message,
63+
})
64+
.catch((error) => {
65+
console.error(`failed to send CREATE_CHAT message for command "${command}"`, error)
66+
})
4267
}
4368
}
4469
})

0 commit comments

Comments
 (0)