Skip to content

Phase 7: SW keep-alive + MCP cache#8

Merged
froggychips merged 1 commit into
mainfrom
review/phase-7-sw-mcp
May 19, 2026
Merged

Phase 7: SW keep-alive + MCP cache#8
froggychips merged 1 commit into
mainfrom
review/phase-7-sw-mcp

Conversation

@froggychips

Copy link
Copy Markdown
Owner

Summary

Две независимые но связанные правки: 1) защита от досрочного выселения service worker'а во время долгих AI-запросов и 2) кэш на MCP-уровне чтобы не лупить gateway повторными вызовами одного и того же author handle.

Что добавлено

  • MCP in-memory cacheMap { 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.
  • Stale request sweep при старте SW: 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.
  • MCP fallback chain DOM scan → MCP → cache уже реализована в content_script:188-204; этот PR добавляет cache на background-уровне (вторая ступень), не дублирует существующую.

Test plan

  • Установить MCP gateway, запустить deepContext запрос → второй раз тот же handle → DevTools Network не показывает повторный MCP-запрос (cached).
  • Подождать 5 мин → cache expired → новый запрос идёт в MCP.
  • Долгий запрос (Slow 3G throttling) >30с → SW не выселяется в середине, sendResponse приходит.
  • chrome://serviceworker-internals → видно периодические "alarm" events каждые 25с пока есть pending callAI.
  • Принудительно kill SW из chrome://extensions во время запроса → следующий поднимет SW, лог SW restart: N stale in-flight request(s) cleared в console.

🤖 Generated with Claude Code

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>
@froggychips froggychips merged commit 7abf196 into main May 19, 2026
@froggychips froggychips deleted the review/phase-7-sw-mcp branch May 19, 2026 08:16

@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: 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".

Comment thread background.js
if (keepAliveActive) return;
keepAliveActive = true;
try {
chrome.alarms?.create('tta-keepalive', { periodInMinutes: 25 / 60 });

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge 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 👍 / 👎.

Comment thread background.js
Comment on lines +38 to +39
const cached = mcpCacheGet(path);
if (cached !== undefined) return cached;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge 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 👍 / 👎.

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