Phase 7: SW keep-alive + MCP cache#8
Conversation
MV3 service worker идёт в idle через ~30с бездействия. Долгий AI-запрос
(>30с) может попасть на выселение SW в середине fetch — pending
sendResponse теряется, UI получает silent fail. Плюс content_script уже
имеет fallback chain MCP → DOM scan, но MCP бьётся повторно при каждом
запросе автора.
- Добавлен MCP in-memory cache в mcpFetch: Map { path → { value,
expiresAt } } с TTL 5 мин и LRU-cap на 200 элементов. SW restart
сбрасывает кэш — это ок, MCP отвечает быстро. Сетевые ошибки не
кэшируются, чтобы следующий вызов мог попробовать снова.
- Добавлен withInflightTracking() wrapper: оборачивает callAI, помечает
запрос в chrome.storage.session, инкрементирует inflightCount.
Регистрирует chrome.alarms каждые 25с пока есть активные запросы —
alarm пробуждает SW и продлевает его жизнь.
- Manifest: добавлен permission "alarms".
- При старте SW проверяет storage.session.tta_inflight_requests на
висяки от прошлой жизни (если SW всё-таки убили вне нашего контроля)
и логирует их в console.warn. Auto-retry не делаем — юзер может уже
видеть ошибку и сам нажал retry.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 58ffb1fd15
ℹ️ 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".
| if (keepAliveActive) return; | ||
| keepAliveActive = true; | ||
| try { | ||
| chrome.alarms?.create('tta-keepalive', { periodInMinutes: 25 / 60 }); |
There was a problem hiding this comment.
Use a supported keep-alive alarm interval
Chrome alarms are limited to firing at most every 30 seconds in current Chrome (and one minute on older versions), so 25 / 60 is not honored as a 25-second heartbeat. In the long-AI-request case this code is meant to protect, the first wake-up can occur only at or after the MV3 service worker's ~30-second idle eviction window, so the worker can still be killed before sendResponse runs; because keepAliveActive is set before creation, there is also no retry/fallback path.
Useful? React with 👍 / 👎.
| const cached = mcpCacheGet(path); | ||
| if (cached !== undefined) return cached; |
There was a problem hiding this comment.
Scope MCP cache entries to the active gateway config
The cache is consulted by path before reading the current MCP URL/token, so a result cached for /status or /tweets/<handle> survives changes made in Options to mcpUrl/mcpToken. If a user fixes a bad token, switches gateways, or restarts the gateway with different data, the extension can keep returning the old success/null/data for up to five minutes instead of querying the newly configured endpoint.
Useful? React with 👍 / 👎.
Summary
Две независимые но связанные правки: 1) защита от досрочного выселения service worker'а во время долгих AI-запросов и 2) кэш на MCP-уровне чтобы не лупить gateway повторными вызовами одного и того же author handle.
Что добавлено
Map { path → { value, expiresAt } }с TTL 5 мин и LRU-cap 200 элементов вmcpFetch. SW restart сбрасывает — это OK, MCP отвечает быстро. Сетевые ошибки не кэшируются.withInflightTracking()— wrapper вокругcallAI. Помечает запрос вchrome.storage.session, инкрементируетinflightCount, регистрируетchrome.alarmsкаждые 25с пока есть активные запросы. Alarm пробуждает SW и продлевает жизнь."alarms"permission в manifest.chrome.storage.session.tta_inflight_requestsчистится сconsole.warn. Auto-retry намеренно не делаем — юзер может уже сам нажать retry.Связь с другими PR
callAI(из PR-3 provider abstraction) теперь всегда идёт черезwithInflightTracking— это и AI-запросы изgenerateReply, иTTA_TEST_KEY, иTTA_HEALTH_CHECK probe.DOM scan → MCP → cacheуже реализована в content_script:188-204; этот PR добавляет cache на background-уровне (вторая ступень), не дублирует существующую.Test plan
chrome://serviceworker-internals→ видно периодические "alarm" events каждые 25с пока есть pending callAI.chrome://extensionsво время запроса → следующий поднимет SW, логSW restart: N stale in-flight request(s) clearedв console.🤖 Generated with Claude Code