Skip to content

fix: Handle "Extension context invalidated" errors from stale content scripts#309

Open
Copilot wants to merge 7 commits intomainfrom
copilot/investigate-sentry-error
Open

fix: Handle "Extension context invalidated" errors from stale content scripts#309
Copilot wants to merge 7 commits intomainfrom
copilot/investigate-sentry-error

Conversation

Copy link
Contributor

Copilot AI commented Mar 3, 2026

拡張機能の更新後に古い content script が動き続けた場合に発生する "Extension context invalidated" エラーを、ストレージ層で適切にハンドリングし、Sentry への報告を抑止します。

Changes

  • BaseStorage.setarea.set() を try/catch でラップし、Extension context invalidated 発生時は警告ログを出力して false を返す(未処理の rejection を伝播させない)
  • BaseStorage.getarea.get() を try/catch でラップし、Extension context invalidated 発生時は警告ログを出力してデフォルト値を返す。また、デフォルト値のクローン処理を遅延評価(値が null/undefined のときのみ実行)に変更してパフォーマンスを改善
  • BaseStorage.getawait 使用時は chrome.runtime.lastError のチェックが不要なため削除(エラーは Promise reject として表面化するため)
  • Sentry.customBeforeSendexception.values[0].value.type の両フィールドをチェックし、Extension context invalidated エラーを Sentry 送信前にグローバルにフィルタ
  • storage/index.test.tsBaseStorage.get/set のコンテキスト無効化ハンドリングのユニットテストを追加(invalidated 時の握りつぶし・その他エラーの再 throw の両ケース)
  • sentry/index.test.tscustomBeforeSend フィルタの挙動テストを追加(該当エラー時に null を返す・非該当時はイベントをそのまま返す)
Original prompt

This section details on the original issue you should resolve

<issue_title>Sentry: Extension context invalidated.</issue_title>
<issue_description>Sentryに報告された以下のエラーについて、原因を調査する。
そして、簡単に修正できそうであれば修正する。
ただし、拡張機能のバージョンアップ時に発生するものでリロードすれば改善されるものではあるので、修正工数が多かったらエラーを無視するだけにする。

Error: Extension context invalidated.
    at Object.set (chrome-extension://nlnhbibaommoelemmdfnkjkgoppkohje/assets/ipc-3k4P-MEh.js:3:3849)
    at f (chrome-extension://nlnhbibaommoelemmdfnkjkgoppkohje/assets/content_script.tsx-CT6Q_HGt.js:763:9116)
    at HTMLDocument.l (chrome-extension://nlnhbibaommoelemmdfnkjkgoppkohje/assets/content_script.tsx-CT6Q_HGt.js:763:9216)
```</issue_description>

## Comments on the Issue (you are @copilot in this section)

<comments>
</comments>


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

Co-authored-by: ujiro99 <677231+ujiro99@users.noreply.github.com>
Copilot AI changed the title [WIP] Investigate and address Sentry extension context issue fix: Handle "Extension context invalidated" errors from stale content scripts Mar 3, 2026
@codecov
Copy link

codecov bot commented Mar 3, 2026

Codecov Report

❌ Patch coverage is 4.76190% with 20 lines in your changes missing coverage. Please review.
✅ Project coverage is 19.02%. Comparing base (920935c) to head (c6da032).
⚠️ Report is 25 commits behind head on main.

Files with missing lines Patch % Lines
packages/extension/src/services/storage/index.ts 7.14% 13 Missing ⚠️
packages/extension/src/lib/sentry/index.ts 0.00% 7 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main     #309      +/-   ##
==========================================
- Coverage   19.03%   19.02%   -0.01%     
==========================================
  Files         312      312              
  Lines       28849    28865      +16     
  Branches     1322     1322              
==========================================
+ Hits         5490     5491       +1     
- Misses      23359    23374      +15     

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

Co-authored-by: ujiro99 <677231+ujiro99@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 3, 2026

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • www.google-analytics.com
    • Triggering command: /opt/hostedtoolcache/node/24.13.1/x64/bin/node /opt/hostedtoolcache/node/24.13.1/x64/bin/node --conditions node --conditions development /home/REDACTED/work/selection-command/selection-command/node_modules/tinypool/dist/entry/process.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Co-authored-by: ujiro99 <677231+ujiro99@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 3, 2026

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • www.google-analytics.com
    • Triggering command: /opt/hostedtoolcache/node/24.13.1/x64/bin/node /opt/hostedtoolcache/node/24.13.1/x64/bin/node --conditions node --conditions development /home/REDACTED/work/selection-command/selection-command/node_modules/tinypool/dist/entry/process.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

@ujiro99 ujiro99 marked this pull request as ready for review March 3, 2026 22:44
@ujiro99 ujiro99 requested a review from Copilot March 3, 2026 22:44
Copy link
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

拡張機能の更新後に古い content script が動き続けた場合に発生する "Extension context invalidated" エラーを、ストレージ層で握りつぶして挙動を安定化し、同種エラーを Sentry 送信対象から除外するためのPRです。

Changes:

  • BaseStorage.get/set"Extension context invalidated" 発生時のハンドリング(get はデフォルト返却、set は false 返却)を追加
  • await 利用箇所の chrome.runtime.lastError チェックを削除し、例外として扱う形に整理
  • Sentry の beforeSend"Extension context invalidated" をフィルタしてイベント送信を抑止

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 6 comments.

File Description
packages/extension/src/services/storage/index.ts storage get/set の例外ハンドリング追加(context invalidated を握りつぶし)
packages/extension/src/lib/sentry/index.ts beforeSend で context invalidated エラーをフィルタして Sentry 送信を抑止

await area.set({ [key]: value })
try {
if (area === chrome.storage.sync) {
await debouncedSyncSet({ [key.toString()]: value })
Copy link

Copilot AI Mar 3, 2026

Choose a reason for hiding this comment

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

chrome.storage.sync 経路は debouncedSyncSetchrome.runtime.lastError をログ出力して Promise を reject しないため、拡張コンテキスト無効化などで実際に失敗してもこの try/catch に入らず true を返し得ます。今回の「invalidated なら false」の意図に揃えるなら、debouncedSyncSet 側で lastError 時に reject する/失敗情報を返す等でエラー伝播を揃えてください。

Suggested change
await debouncedSyncSet({ [key.toString()]: value })
await new Promise<void>((resolve, reject) => {
area.set({ [key]: value }, () => {
if (chrome.runtime.lastError != null) {
reject(chrome.runtime.lastError)
} else {
resolve()
}
})
})

Copilot uses AI. Check for mistakes.
Comment on lines +139 to +141
if (isContextInvalidated(error)) {
console.warn("Extension context invalidated, ignoring storage get")
return defaultValue as T
Copy link

Copilot AI Mar 3, 2026

Choose a reason for hiding this comment

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

この console.warnselectionchange など高頻度で呼ばれる経路から発火し得るため、コンテキスト無効化中に大量ログになる可能性があります。1回だけ警告する(フラグで抑制/レート制限)か、必要なら error も併記しつつ最小限に抑える形にすると運用上安全です。

Copilot uses AI. Check for mistakes.
Comment on lines +157 to +160
if (isContextInvalidated(error)) {
console.warn("Extension context invalidated, ignoring storage set")
return false
}
Copy link

Copilot AI Mar 3, 2026

Choose a reason for hiding this comment

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

この console.warn も高頻度に呼ばれる可能性があるため、コンテキスト無効化中にログスパムになり得ます。警告を1回に抑制する(フラグ/レート制限)など、運用上のノイズを抑える対応を検討してください。

Copilot uses AI. Check for mistakes.
Comment on lines +138 to +142
} catch (error) {
if (isContextInvalidated(error)) {
console.warn("Extension context invalidated, ignoring storage get")
return defaultValue as T
}
Copy link

Copilot AI Mar 3, 2026

Choose a reason for hiding this comment

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

BaseStorage.get/set にコンテキスト無効化時の分岐(デフォルト返却 / false返却)が追加されていますが、packages/extension/src/services/storage/index.test.ts では現状この分岐の回帰検知ができません。area.get/area.setExtension context invalidated で reject したときに握りつぶすこと、他のエラーは再throwすることをユニットテストで追加してください。

Copilot generated this review using guidance from repository custom instructions.
Copy link
Owner

Choose a reason for hiding this comment

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

@copilot apply changes based on this feedback

Copy link
Contributor Author

Choose a reason for hiding this comment

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

以下のテストを index.test.ts に追加しました。(e570696)

  • BS-GET-01: area.get が "Extension context invalidated" で reject → デフォルト値を返す
  • BS-GET-02: area.get が他のエラーで reject → 再throw
  • BS-SET-01: area.set が "Extension context invalidated" で reject → false を返す
  • BS-SET-02: area.set が他のエラーで reject → 再throw

Comment on lines +71 to +75
const exceptionValue = event.exception?.values?.[0]
if (
exceptionValue?.value?.includes("Extension context invalidated") ||
exceptionValue?.type?.includes("Extension context invalidated")
) {
Copy link

Copilot AI Mar 3, 2026

Choose a reason for hiding this comment

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

"Extension context invalidated" のフィルタが追加されていますが、index.test.ts に beforeSend フィルタの挙動(該当時に null が返って送信されない/非該当時はイベントが返る)を検証するテストが見当たりません。回帰防止のためテスト追加をお願いします。

Copilot generated this review using guidance from repository custom instructions.
Copy link
Owner

Choose a reason for hiding this comment

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

@copilot apply changes based on this feedback

Copy link
Contributor Author

Choose a reason for hiding this comment

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

customBeforeSendTestUtils にエクスポートし、以下のテストを追加しました。(47fb946)

  • ST-BF-01: value に "Extension context invalidated" を含む → null を返す
  • ST-BF-02: type に "Extension context invalidated" を含む → null を返す
  • ST-BF-03: 無関係なエラー → イベントをそのまま返す
  • ST-BF-04: exception.values が存在しない → イベントをそのまま返す

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
…ling

Co-authored-by: ujiro99 <677231+ujiro99@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 3, 2026

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • www.google-analytics.com
    • Triggering command: /opt/hostedtoolcache/node/24.13.1/x64/bin/node /opt/hostedtoolcache/node/24.13.1/x64/bin/node --conditions node --conditions development /home/REDACTED/work/selection-command/selection-command/node_modules/tinypool/dist/entry/process.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Co-authored-by: ujiro99 <677231+ujiro99@users.noreply.github.com>
Copy link
Contributor Author

Copilot AI commented Mar 3, 2026

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • www.google-analytics.com
    • Triggering command: /opt/hostedtoolcache/node/24.13.1/x64/bin/node /opt/hostedtoolcache/node/24.13.1/x64/bin/node --conditions node --conditions development /home/REDACTED/work/selection-command/selection-command/node_modules/tinypool/dist/entry/process.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

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.

Sentry: Extension context invalidated.

3 participants