Mark dbd977c815 feat(01-11): wave-2 — Puppeteer harness scaffolding + A0 GREEN, popup-bridge architecture
Task 3 of Plan 01-11 (Puppeteer UAT harness).

Harness file tree (tests/uat/):
- harness.test.ts: tsx-runnable top-to-bottom harness entry point.
  Runs A0 inline (filesystem grep gate, abort-on-fail T-1-11-01),
  then launches Chrome + opens popup bridge + queries manifest, then
  iterates A1-A13 stubs. Each stub throws "NOT YET IMPLEMENTED —
  Plan 01-11 Task N wires this assertion". Exit code = 0 on full
  pass, 1 otherwise. Final line: "UAT harness: N/14 assertions passed".
- lib/launch.ts: launchHarnessBrowser() — wraps puppeteer.launch with
  enableExtensions:[dist-test/], headless default (HEADLESS=0
  override), --no-sandbox + --auto-select-desktop-capture-source flags.
  Polls browser.extensions() until the extension registers (empirically
  ~100ms but the first call right after launch returns Map(0)).
  Opens both a blank page (for triggerExtensionAction) AND the popup
  page (the bridge surface). Returns { browser, extension, extensionId,
  sw, downloadsDir, page, popup }.
- lib/extension.ts: waitForOffscreenTarget + attachToOffscreen +
  countOffscreenTargets. Offscreen attach uses target.type() ===
  'background_page' + .asPage() (NOT .page() — RESEARCH §4 Pitfall 1).
- lib/sw.ts: chrome.* state queries via the POPUP page handle (NOT
  the WebWorker handle — see architecture note below). getBadgeText,
  getPopup, getManifest, getIconSize, getIsRecording (side-channeled
  through badge text), fireOnStartup (via __mokoshTestQuery bridge),
  sendSyntheticRecordingError, getNotificationSnapshot (via bridge),
  keepalivePing (no-op message to wake SW for ~30s).
- lib/offscreen.ts: getDisplaySurface, simulateUserStop (the
  dispatchEvent('ended') path per RESEARCH §7 BLOCKER — DO NOT REFACTOR
  to track.stop()), getSegmentCount.
- lib/assertions.ts: runAssertion(idx, name, buffers, fn) wrapper —
  records pass/fail/duration; on failure dumps last 30 lines of SW
  + offscreen console buffers to stderr before rethrowing. assertEqual
  / assertMatch / assertTrue / assertGte / waitFor polling helper.
- lib/zip.ts: jszip-based assertArchiveShape + extractEntryToFile for
  assertions 12 + 13.
- README.md: runtime + local-debug + CI semantics + locale gotcha
  + dev-dep size note + assertion catalog table.
- tsconfig.json: per-tree type-check config (mirrors root tsconfig.json
  compiler options but includes the harness tree explicitly).

Architecture refinement (DEVIATION from RESEARCH §1 — Rule 1+3 inline fix):
- RESEARCH §1 sketched `sw.evaluate(() => chrome.action.getBadgeText({}))`
  as the chrome.* query path. Empirical probes during Task 3 execution
  against Puppeteer 25.0.2 + Chrome 148 + --headless=true revealed two
  blockers:
    1. Puppeteer's WebWorker.evaluate runs in an ISOLATED WORLD that
       carries SW globals (clients, registration, ...) but NOT the
       extension's full chrome.* API surface. Object.keys(chrome) inside
       sw.evaluate returns ["loadTimes","csi"] — the public webpage
       chrome, not the extension chrome.
    2. Chrome 148's headless mode aggressively suspends MV3 service
       workers; subsequent swTarget.worker() calls return
       "Protocol error: No target with given id found".
- WORKAROUND: open the popup page (chrome-extension://<id>/src/popup/
  index.html) as a separate Puppeteer Page. The popup has full
  chrome.* access (it's an extension context with same privileges as
  the SW) AND stable Puppeteer lifetime. For SW-globalThis state
  (__mokoshTest in the SW isolate, NOT in the popup), bridge via
  chrome.runtime.sendMessage. The popup sends
  { type: '__mokoshTestQuery', op: 'snapshot' | 'fire-on-startup' |
  'handler-types' }; the SW hook's onMessage handler responds.
- Bridge implementation added to src/test-hooks/sw-hooks.ts — registers
  AFTER the production listeners so it never intercepts production
  messages (__mokoshTest* type is unambiguously test-only). Tier-1
  grep gate (no-test-hooks-in-prod-bundle.test.ts) continues to enforce
  ZERO __mokoshTest occurrences in dist/ — the bridge handler is
  tree-shaken alongside the rest of the hook module via the
  __MOKOSH_UAT__ gate.

Other configuration changes:
- vitest.config.ts: exclude tests/uat/** from vitest discovery. The
  Puppeteer harness is invoked via `npm run test:uat` (not vitest);
  running it under vitest would try to launch real Chrome inside a
  vitest worker. The .test.ts suffix is retained for editor +
  naming-convention consistency with the rest of the tree.

Verification:
- npx tsc --noEmit (src/): exit 0
- npx tsc --noEmit -p tests/uat: exit 0
- npm run build: exit 0
- grep -rln '__mokoshTest|simulateUserStop|getSegmentCount|setCurrentStream|setSegmentCountGetter|__mokoshTestQuery|__mokoshKeepalive' dist/: ZERO matches
- npm run build:test: exit 0; dist-test/ populated with the new bridge code
- SKIP_BUILD=1 npx vitest run: 89/89 GREEN
- SKIP_PROD_REBUILD=1 npx tsx tests/uat/harness.test.ts:
  → A0 [PASS]: production bundle has no test-hook leaks (19ms)
  → Browser launches; popup opens; manifest read succeeds
  → A1-A13 [FAIL]: NOT YET IMPLEMENTED — Plan 01-11 Task N wires this
  → "UAT harness: 1/14 assertions passed, 13 failed (first failure: A1)"
  → Exit code: 1 (expected — 13 RED stubs intentional)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 09:14:58 +02:00

AI Call Recorder - Браузерное расширение для записи сессий операторов

Фаза 1 — Локальная запись + экспорт архива

Установка и запуск

Разработка

# Установка зависимостей
npm install

# Сборка для разработки с HMR
npm run dev

# Сборка для продакшена
npm run build

Установка расширения в Chrome

  1. Соберите проект:

    npm run build
    
  2. Откройте Chrome и перейдите по адресу: chrome://extensions/

  3. Включите "Режим разработчика" (Developer mode) в правом верхнем углу

  4. Нажмите кнопку "Загрузить распакованное расширение" (Load unpacked)

  5. Выберите папку dist в корне проекта

  6. Расширение установлено!

Использование

  1. При первом открытии popup расширение запросит разрешение на запись экрана

  2. Разрешение обязательно для работы расширения

  3. Расширение автоматически начнет запись:

    • Видео: последние 30 секунд (кольцевой буфер)
    • DOM-события через rrweb: последние 10 минут
    • Лог действий пользователя: последние 10 минут
  4. Для сохранения отчета об ошибке:

    • Нажмите на иконку расширения
    • Нажмите кнопку "Сохранить отчёт об ошибке"
    • Архив автоматически загрузится в папку "Загрузки"

Структура архива

Архив session_report_YYYY-MM-DD_HH-MM-SS.zip содержит:

session_report_2025-05-15_14-32-10.zip
├── video/
│   └── last_30sec.webm         # склеенные чанки видеобуфера
├── rrweb/
│   └── session.json            # массив DOM-событий rrweb
├── logs/
│   └── events.json             # лог действий пользователя
├── screenshot.png              # скриншот в момент сохранения
└── meta.json                   # метаданные сессии

Технический стек

  • Тип расширения: Chrome Extension, Manifest V3
  • Service Worker: Background script (Manifest V3)
  • Захват экрана: chrome.tabCapture API
  • Захват DOM: rrweb (npm: rrweb)
  • Лог событий: Content Script
  • Упаковка архива: JSZip (npm: jszip)
  • Сохранение файла: chrome.downloads API
  • Хранение буфера: In-memory (Service Worker + Content Script)
  • Build: Vite + crxjs + TypeScript

Особенности

Маскирование чувствительных данных

  • Пароли (input[type=password]) маскируются автоматически в rrweb и логах
  • Поля с атрибутом data-sensitive="true" также маскируются в rrweb

Записываемые события

Пользовательские события

  • click — клик по любому элементу
  • input — изменение значения поля (без паролей)
  • navigation — переходы по страницам (popstate, hashchange, History API)
  • js_error — JavaScript ошибки (window.onerror, unhandledrejection)
  • network_error — сетевые ошибки (fetch/XHR с кодом ответа >= 400)

Кольцевой буфер

  • Видео: 30 секунд, первый чанк (WebM заголовок) хранится всегда
  • rrweb события: 10 минут, максимум 5000 событий
  • Пользовательские события: 10 минут

Память

  • Ожидаемое потребление: ~5-10 МБ в фоновом режиме

Критерии приёмки Фазы 1

  • Расширение устанавливается в Chrome без ошибок
  • Видеобуфер непрерывно работает на любой вкладке
  • В буфере всегда есть не более 30 секунд видео
  • rrweb пишет DOM-события без ошибок на типовых страницах
  • Лог событий фиксирует клики, навигацию и сетевые ошибки
  • При нажатии кнопки архив скачивается в "Загрузки" за < 5 секунд
  • Архив открывается, last_30sec.webm воспроизводится в браузере
  • Пароли не попадают в лог и rrweb-снимки
  • RAM-потребление расширения не превышает 50 МБ в фоне

Отладка

Console Logs

Расширение пишет подробные логи в консоль:

  • Service Worker: Chrome DevTools → Extensions → Service Worker → Console
  • Content Script: Chrome DevTools на любой странице → Console
  • Popup: Правый клик по popup → Проверить

Структура проекта

ai-call-extension/
├── src/
│   ├── background/          # Service Worker
│   │   └── index.ts
│   ├── content/            # Content Script
│   │   └── index.ts
│   ├── popup/              # Popup UI
│   │   ├── index.html
│   │   ├── index.ts
│   │   └── style.css
│   └── shared/             # Общие типы и утилиты
│       ├── types.ts
│       └── logger.ts
├── icons/                  # Иконки расширения
├── dist/                   # Собранные файлы
├── manifest.json           # Manifest расширения
├── vite.config.ts          # Конфигурация Vite
├── tsconfig.json           # Конфигурация TypeScript
└── package.json

Лицензия

MIT

Контакты

Для вопросов и предложений обращайтесь в support.

Description
No description provided
Readme 8 MiB
Languages
TypeScript 91%
HTML 3.4%
CSS 2.8%
Shell 2%
JavaScript 0.8%