Commit Graph

149 Commits

Author SHA1 Message Date
Nick Shirokov 26888a07d5 chore(repo): нормализация EOL к LF + .gitattributes
Приводим авторский контент (.ps1/.psm1/.py/.mjs/.md/.json, пин .bsl)
к единому LF и закрепляем политикой в .gitattributes. Инструмент правки
всегда пишет LF, поэтому единый LF убирает EOL-шум в диффах, ложные
срабатывания blame и налог на ручную синхронизацию CRLF-файлов.

BOM на .ps1 сохранён (git с eol=lf меняет только CR<->LF, BOM не трогает).
Данные 1С (*.xml) и бинарники под нормализацию не берём.

Гейт: PS-порт 459/459, Python-порт 459/459, web-test E2E 22/22 (с пересборкой стенда).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 14:22:45 +03:00
Nick Shirokov 8fd5544abd refactor(web-test): bump browser.mjs до v1.18 (финализация S1–S6)
Завершён рефакторинг §0.5 п.5 родительского плана (вынос inline DOM в
dom/). Итоговые метрики:

| Файл              | До (LOC, evals) | После (LOC, evals) |
|-------------------|-----------------|--------------------|
| row-fill.mjs      | 1235 / 47       |  793 / 1           |
| select-value.mjs  |  959 / 25       |  827 / 5           |
| filter.mjs        |  390 / 17       |  256 / 0           |
| Σ engine hot      | 2584 / 89       | 1876 / 6           |

Снижение LOC −708 (−27%), inline page.evaluate −83 (−93%).

dom/ расширился с 7 до 11 файлов: новые edd.mjs, edit-state.mjs,
filter.mjs, grid-edit.mjs; расширены forms.mjs (+16 функций) и
grid.mjs (+4 функции).

Engine-модули стали orchestrator-ами. Публичный API browser.mjs —
56 экспортов, без изменений. Полный регресс зелёный после каждого
этапа S1–S6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 21:32:09 +03:00
Nick Shirokov c930b4b04d refactor(web-test): spreadsheet выделен в собственную папку
SpreadsheetDocument (отчёты, печатные формы) — другой домен, чем form-grid
(табличные части документов, списки). Раньше лежал внутри table/, что
было обманчиво.

  engine/table/spreadsheet.mjs → engine/spreadsheet/spreadsheet.mjs

Структура engine/:
  core/         плумбинг движка (state, wait, errors, session, click, ...)
  forms/        работа с формами (fill, close, select-value, state)
  nav/          навигация
  table/        form-grid (grid, row-fill, filter, grid-toggle)
  spreadsheet/  SpreadsheetDocument
  recording/    запись + overlays

В будущем при росте spreadsheet можно распилить — engine/spreadsheet/cells.mjs,
engine/spreadsheet/scroll.mjs и т.д. без переименований.

11-report регресс зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 16:52:15 +03:00
Nick Shirokov 8bdcb9e664 refactor(web-test): form-state переехал из core/ в forms/
getFormState — высокоуровневая операция «прочитать состояние формы»,
семантически в forms/ ближе чем в core/ (foundational плумбинг движка).

  engine/core/form-state.mjs → engine/forms/state.mjs

Все 11 importer'ов обновлены. Внутри state.mjs пути исправлены:
'./state.mjs' → '../core/state.mjs', './errors.mjs' → '../core/errors.mjs'.

03-fillfields регресс зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 16:48:08 +03:00
Nick Shirokov a24c39b6de refactor(web-test): этап E.13 — финализация (v1.17 + чистый facade + чистка)
1. Версия v1.16 → v1.17 во всех заголовках движка.

2. browser.mjs стал чистым facade — только re-exports, 0 функций определено.
   Было: 249 LOC с 4 настоящими функциями (saveClipboard, restoreClipboard,
   pasteText, getFormState) — теперь 57 LOC чистых re-export'ов.

3. engine/core/clipboard.mjs — новый модуль:
     pasteText + saveClipboard + restoreClipboard (~85 LOC, был в browser.mjs).

4. engine/core/form-state.mjs — новый модуль:
     getFormState — центральный читатель состояния формы (~30 LOC).

5. Убрано 12 циклических импортов из engine/* → ../../browser.mjs:
   - Все читатели pasteText теперь импортят из engine/core/clipboard.mjs
   - Все читатели getFormState — из engine/core/form-state.mjs
   - session.mjs → nav/navigation.mjs (getPageState напрямую)
   - filter.mjs → core/click.mjs (clickElement напрямую)
   Граф зависимостей стал деревом (без обратных рёбер).

6. Убраны _-префиксы у 9 функций, которые стали приватными внутри своих
   модулей (раньше _ означало "приватная для browser.mjs"):
     _detectPlatformDialogs → detectPlatformDialogs
     _closePlatformDialogs → closePlatformDialogs
     _parseErrorStack → parseErrorStack
     _fetchStackViaReport → fetchStackViaReport
     _fetchStackViaHamburger → fetchStackViaHamburger
     _logoutSlot → logoutSlot
     _saveActiveSlot → saveActiveSlot
     _activateSlot → activateSlot
     _attachSessionListeners → attachSessionListeners

Публичный API: 56 экспортов, идентичный исходному.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 16:25:15 +03:00
Nick Shirokov 8739d1d15c refactor(web-test): структура — engine/ wrapper для внутренних модулей
Перенос всей внутрянки движка под scripts/engine/:
  - core/, forms/, nav/, table/, recording/ → engine/<same>/

Публичные entry-точки остаются в scripts/ корне без изменений:
  - browser.mjs, dom.mjs, run.mjs — компат не ломаем.

Симметричный layout, легко читать с первого взгляда:
  scripts/
    browser.mjs, dom.mjs, run.mjs    ← публичные entries
    engine/                          ← внутренности движка
    (dom/, cli/ — место под будущий распил dom.mjs / run.mjs)

Технические правки после переезда:
  - browser.mjs: ./core/... → ./engine/core/... (23 импорта)
  - engine/*/* модули: ../browser.mjs → ../../browser.mjs (11 импортов)
  - engine/*/* модули: ../dom.mjs → ../../dom.mjs (12 импортов)
  - engine/recording/capture.mjs: dynamic import('../browser.mjs')
    → import('../../browser.mjs')
  - engine/core/state.mjs: projectRoot пересчитан (5 → 6 уровней вверх)
  - Git rename detection срабатывает — история файлов сохраняется

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 16:03:20 +03:00
Nick Shirokov f31770d79c refactor(web-test): этап D.12 — fillTableRow → row-fill.mjs, deleteTableRow → grid.mjs
table/row-fill.mjs (~1230 LOC): fillTableRow целиком, как entry-point.
table/grid.mjs: добавлен deleteTableRow + расширены импорты (clickElement,
dismissPendingErrors, waitForStable, getFormState).

Дальнейший распил fillTableRow на под-хелперы (trySelect/readVisibleRows/
pickValueWithOptionalType/enterEditMode/fillCellSequentially per плана §12.1-12.3)
отложен — при необходимости создаём table/row-fill/*.mjs subfolder.

browser.mjs: 1532 → 249 LOC (-84% от baseline 6293).
05-table регресс зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 15:02:47 +03:00
Nick Shirokov a5c0be6766 refactor(web-test): переименование — readTable в table/grid.mjs
readTable читает form-grid (.gridLine/.gridBody — табличные части на форме,
списки), а не SpreadsheetDocument. Имя файла table/spreadsheet.mjs было
обманчиво. Разделяем домены:

  table/grid.mjs        ← readTable (form-grid операции, готово
                         для fillTableRow + deleteTableRow в D.12)
  table/spreadsheet.mjs ← readSpreadsheet + cell helpers (только
                         SpreadsheetDocument — отчёты, печатные формы)

Поведение 1-в-1. browser.mjs re-export обновлён.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 14:59:28 +03:00
Nick Shirokov 0ba8127d52 refactor(web-test): этап C.11 — table/spreadsheet.mjs + table/filter.mjs
table/spreadsheet.mjs (~580 LOC):
  - readTable, readSpreadsheet
  - scanSpreadsheetCells, buildSpreadsheetMapping (private)
  - scrollSpreadsheetToCell, clickSpreadsheetCell, findSpreadsheetCellByText

table/filter.mjs (~390 LOC): filterList, unfilterList

После C.11 + C.10 clean-up:
  - core/click.mjs импортит clickSpreadsheetCell/findSpreadsheetCellByText
    напрямую из table/spreadsheet.mjs (а не из browser.mjs)
  - browser.mjs больше не реэкспортирует эти два — публичный API
    остаётся 56 экспортов как до рефакторинга
  - Добавил import { clickElement } в browser.mjs для внутренних вызовов
    из fillTableRow/deleteTableRow

browser.mjs: 2470 → 1532 LOC (≈75% от исходных 6293).
05-table + 09-filter регресс зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 13:14:49 +03:00
Nick Shirokov 9ee0473412 refactor(web-test): этап C.10 — clickElement → core/click.mjs (целиком)
clickElement (~300 LOC) перенесён единым блоком в core/click.mjs.
Поведение 1-в-1. Внутри остаётся всё ветвление (spreadsheet, submenu,
gridGroup/Parent, gridTreeNode, gridRow, tab, button) — разнос на
forms/click-form.mjs + nav/click-popup.mjs + finer table-toggle
отложен на E.13 для безопасности.

clickSpreadsheetCell + findSpreadsheetCellByText временно exported из
browser.mjs (нужны core/click.mjs). На C.11 они переедут в
table/spreadsheet.mjs, экспорт из browser.mjs можно будет убрать.

browser.mjs: 2768 → 2470 LOC.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 13:07:22 +03:00
Nick Shirokov cbd580a0bd refactor(web-test): этап C.9 — выделить forms/fill.mjs + forms/close.mjs
forms/fill.mjs (~140 LOC): fillFields, fillField
forms/close.mjs (~50 LOC): closeForm
clickElement остаётся в browser.mjs до C.10.

Допиленные импорты после первого прохода:
  - fill.mjs: readFormScript, normYo (из dom/state — забыл при экстракции)
  - close.mjs: recorder (используется для паузы 500ms при confirmation
    во время записи)

03-fillfields регресс зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 13:04:09 +03:00
Nick Shirokov 3a6d5abffc refactor(web-test): этап C.8 — выделить forms/select-value.mjs
Перенос selectValue + helpers из browser.mjs (~960 LOC):
  - scanGridRows, dblclickAndVerify, advancedSearchInline
  - pickFromSelectionForm, isTypeDialog, pickFromTypeDialog (экспортируются —
    вызываются из fillFields/fillTableRow в browser.mjs)
  - fillReferenceField (экспортируется — вызывается из fillFields)
  - selectValue

Двумя слайсами вокруг fillFields/fillField/clickElement/closeForm, которые
остаются в browser.mjs до этапов C.9/C.10.

browser.mjs: 4095 → 2933 LOC. 56 публичных экспортов.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 12:28:31 +03:00
Nick Shirokov c4b1aee9c9 refactor(web-test): этап C.7 — выделить nav/navigation.mjs
Перенос navigation-функций из browser.mjs (~240 LOC):
  - getPageState, getSections, navigateSection, getCommands
  - openCommand, switchTab
  - openFile (Ctrl+O + security dialog flow)
  - navigateLink (Shift+F11 e1cib paste)
  - E1CIB_TYPE_MAP, E1CIB_APP_TYPES, normalizeE1cibUrl (приватные)

Цикл с browser.mjs (getFormState, pasteText) — статический ESM-импорт,
разрешается во время вызова (binding live). core/session.mjs продолжает
импортить getPageState из browser.mjs через re-export.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 12:16:56 +03:00
Nick Shirokov 12c5cf5e66 fix(web-test): TDZ в selectValue (detectNewForm) + missing import clipboardWarnLogged
1. В selectValue локальный const detectNewForm = () => ... объявлялся ниже
   composite-type ветки, которая его вызывала → TDZ ReferenceError "Cannot
   access 'detectNewForm' before initialization". Хелпер поднят в начало
   функции, дубликат-объявление убрано.

2. clipboardWarnLogged читается в restoreClipboard (line 92), но не был
   в списке импортов из core/state.mjs (импортировался только setter).
   ReferenceError срабатывал только когда clipboard.read() возвращал
   ошибку — в первом A-регрессе ветка не активировалась случайно.

Регресс 18/19 (одна flake в 11-report — readSpreadsheet timing).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-26 11:58:26 +03:00
Nick Shirokov 6fb5b9f617 refactor(web-test): этап B.6 — table/grid-toggle.mjs (icon detection shared)
В clickElement две ветки (gridGroup/gridParent + gridTreeNode) имели
почти идентичные page.evaluate-блоки: найти gridLine под target.y,
получить иконку-разворачивалку, вернуть её центр + isExpanded.

table/grid-toggle.mjs:
  - getGridToggleIcon(target, formNum, { iconSelector, isExpandedExpr })
  - shouldClickToggle(iconInfo, expand, toggle)

Поведение 1-в-1. Селекторы и isExpanded-критерий передаются параметрами:
  - groups: '.gridListH, .gridListV' + icon.classList.contains('gridListV')
  - trees:  '.gridBoxImg [tree="true"]' + bg.includes('gx=0')

Экономия ~30 LOC дублей.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:44:18 +03:00
Nick Shirokov 9ac0cb3b87 refactor(web-test): этап B.5.5 — ввести returnFormState (выборочно применить)
core/helpers.mjs: returnFormState(extras) — стандартный хвост action-функций:
getFormState + Object.assign(extras) + checkForErrors → state.errors. Унифицирует
~15 hand-written копий и закрывает R1/R2/R3 (state.errors теперь добавляется
автоматически у любого пользователя хелпера).

В этом коммите конвертированы только 2 простейших P1-сайта (openCommand,
второй handle в navigateLink) — без extras между getFormState и err-проверкой.
Остальные 30+ сайтов сложнее (state.X между, разные return-shape, wrapped
fillFields) — будут мигрированы органически при переносе clickElement/
selectValue/closeForm в forms/* на этапе C.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:42:23 +03:00
Nick Shirokov e215957344 refactor(web-test): этап B.5.4 — readEdd хелпер (2 копии в fillReferenceField)
В fillReferenceField было два места с одинаковым page.evaluate-скриптом
чтения #editDropDown (DLB-popup перед paste и autocomplete после Ctrl+V).

core/helpers.mjs: readEdd() → { visible, items?: [{ name, x, y }] }.

selectValue использует свой clickEddItem через dispatchEvent (bypass div.surface) —
оставлен как есть, специфика API там сильно отличается.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:35:24 +03:00
Nick Shirokov 09b2084672 refactor(web-test): этап B.5.3 — detectNewForm хелпер (3 копии → 1)
В fillReferenceField, selectValue и fillTableRow была одна и та же логика:
сканировать DOM на наличие элемента с id="form{N}_*" где N > prevFormNum.
Две вариации: strict (только visible interactive — input.editInput/a.press)
и broad (любой [id], учитывает type-dialogs с пустыми button-id).

core/helpers.mjs: detectNewForm(prevFormNum, { strict }) → number|null.
Внутри функций оставлены тонкие локальные обёртки (для совместимости
с уже использующейся сигнатурой без аргументов) — будут убраны на C.8/D.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:34:21 +03:00
Nick Shirokov 3fe038277f refactor(web-test): этап B.5.2 — findFieldInputId хелпер (4 копии → 1)
В selectValue было 4 одинаковых блока поиска input-элемента поля
по имени (form{N}_{name} либо form{N}_{name}_i0 для refs):
clear-ветка, composite-type-ветка, F4-fallback, "last resort" F4.

core/helpers.mjs: findFieldInputId(formNum, fieldName) → string|null.
~30 LOC дублей убрано, поведение 1-в-1.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:33:15 +03:00
Nick Shirokov 5b6243bbcc refactor(web-test): этап B.5.1 — safeClick хелпер вместо 3 копий pointer-events retry
В fillReferenceField, clickElement и DLB-ветке selectValue был один и тот же
паттерн: page.click → catch 'intercepts pointer events' → force-click →
catch снова → Escape + retry. Три копии (плюс одна с dismissPendingErrors).

core/helpers.mjs (новый): safeClick(selector, { timeout, dismissErrors }).
Экономия ~60 LOC дублей. Поведение 1-в-1 (dismissErrors:true только в
fillReferenceField — там единственное место, где исходно было).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:31:45 +03:00
Nick Shirokov 2cba13a8cc fix(web-test): экспортировать _detectPlatformDialogs/_closePlatformDialogs из core/errors.mjs
После A.3 эти helpers стали приватными в core/errors.mjs, но getFormState
(browser.mjs:408) и closeForm (browser.mjs:2168) их по-прежнему вызывают —
ловили ReferenceError на каждое действие. Делаем их экспортируемыми
и импортируем в browser.mjs. Имя с подчёркиванием сохраняется до этапа E.13
(финальная чистка). Регресс 19/19.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:25:54 +03:00
Nick Shirokov fca65ef658 refactor(web-test): этап A.4 — выделить core/session.mjs
Перенос session-функций из browser.mjs (~380 LOC):
  - connect, disconnect, attach, detach, getSession
  - createContext, setActiveContext, listContexts, getActiveContext,
    hasContext, closeContext
  - findExtension (приватная)
  - _logoutSlot, _saveActiveSlot, _activateSlot, _attachSessionListeners
    (приватные multi-context хелперы)

Session-модуль зависит от core/state, core/errors (closeModals),
recording/capture (stopRecording) и циклически от browser.mjs
(getPageState — переедет в nav/navigation.mjs на этапе C.7).
ESM live-binding делает цикл безопасным: getPageState вызывается
только внутри async функций, а не на этапе загрузки модуля.

browser.mjs: 4251 LOC, 56 публичных экспортов. Завершает Чекпоинт A.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:12:07 +03:00
Nick Shirokov 4f01f01286 refactor(web-test): этап A.3 — выделить core/wait.mjs + core/errors.mjs
core/wait.mjs (123 LOC):
  - waitForStable: smart DOM-stability polling
  - waitForCondition: JS-expression polling
  - startNetworkMonitor: CDP network-activity monitor

core/errors.mjs (336 LOC):
  - closeModals, dismissPendingErrors, checkForErrors, fetchErrorStack
  - Платформенные диалоги: _detectPlatformDialogs, _closePlatformDialogs
  - _parseErrorStack, _fetchStackViaReport, _fetchStackViaHamburger (приватные)

browser.mjs импортирует их для внутреннего использования и re-export'ит
только fetchErrorStack (исходно публичный). Остальные функции остаются
приватными — публичный API не меняется (56 экспортов).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:10:31 +03:00
Nick Shirokov 398c515390 refactor(web-test): этап A.2 — вынести recording/* в отдельные модули
Перенос ~1200 LOC из browser.mjs в recording/{tts,captions,capture,highlight,narration}.mjs:
  - tts.mjs: resolveFfmpeg, resolveEdgeTts, edge/openai/elevenlabs providers,
    getTtsProvider, getAudioDuration, generateSilence
  - captions.mjs: showCaption/hideCaption/getCaptions, showTitleSlide/
    hideTitleSlide, showImage/hideImage
  - capture.mjs: screenshot, wait, isRecording, startRecording, stopRecording
  - highlight.mjs: highlight, unhighlight, setHighlight, isHighlightMode
  - narration.mjs: addNarration

browser.mjs стал тоньше на 1200 строк, re-export через `export { ... } from './recording/*.mjs'`.
Публичный API сохранён (56 экспортов). state.mjs нормализован на CRLF.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:07:32 +03:00
Nick Shirokov cecf4dd9a2 refactor(web-test): этап A.1 — выделить module-level state в core/state.mjs
Состояние движка (browser, page, sessionPrefix, seanceId, recorder, контексты,
константы, normYo, isConnected/ensureConnected/getPage) переехало в
core/state.mjs. Импортируется как live-binding; присваивания в browser.mjs
конвертированы в setX(...) — ESM imports read-only.

Публичный API не меняется (56 экспортов). Регресс 19/19 зелёный.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 22:00:53 +03:00
Nick Shirokov bb2f8fb29e feat(web-test): сохранять и восстанавливать буфер обмена вокруг паст
Тесты активно используют OS clipboard (`writeText` + Ctrl+V — единственный
способ добиться trusted-paste для autocomplete справочников и кириллицы).
При локальном запуске это перетирало пользовательский буфер. Теперь:

- `pasteText(text, {confirm, postDelay})` в browser.mjs делает узкое окно
  save → writeText → confirm-key → restore вокруг каждой пасты (~ms).
- Save/restore через `navigator.clipboard.read()`/`write()` — все MIME
  (текст, картинка, HTML), blob'ы стэшатся на `window` без CDP-сериализации.
- 14 callsites переведены на helper.
- При failure save'а (CF_HDROP из Проводника не виден через web-API) restore
  явно очищает буфер, чтобы тестовое значение не протекало.
- Опт-аут: CLI `--no-preserve-clipboard`, env `WEB_TEST_PRESERVE_CLIPBOARD=0`,
  `preserveClipboard: false` в `webtest.config.mjs`.

Регресс tests/web-test — 6 прогонов 19/19 passed.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 20:12:14 +03:00
Nick Shirokov eb87be5c04 feat(web-test): M8 — per-context lifecycle (closeContext + afterOpenContext/beforeCloseContext)
browser.mjs:
- + closeContext(name): logout slot + close page (tab) или context (window),
  удаление из реестра. Throw если name неактивен (рулило: nicht den aktiven
  closen, recorder always attached к active → invariant простой).
- _logoutSlot(slot, waitMs) — извлечён из disconnect, переиспользуется в
  closeContext.

run.mjs:
- ensureContext() после createContext вызывает hooks.afterOpenContext(ctx, name, spec).
- wrapCloseContextHook() оборачивает ctx.closeContext (и каждую scoped-обёртку)
  чтобы перед browser.closeContext fir'ить hooks.beforeCloseContext.
- Финальный teardown в finally: для всех живых контекстов кроме первого
  (survivor) — beforeCloseContext + closeContext; для survivor только хук,
  его закрывает disconnect().

_hooks.mjs v0.5:
- afterOpenContext инжектит persistent DOM-badge с displayName в правый
  верхний угол page — в записанном видео всегда видно, какой контекст.
- beforeCloseContext counter-only.
- _state расширен полями afterOpenContext / beforeCloseContext.

15-multi-context-handover.test.mjs:
- +2 шага: closeContext('b') после handover, попытка closeContext(active)
  ловится throw'ом с проверкой message.

00-hooks.test.mjs:
- +1 ассерт: afterOpenContext >= 1 (default уже создан), beforeCloseContext === 0
  в теле первого теста.

spec §6:
- Раздел «Контекстный уровень» (afterOpenContext / beforeCloseContext + правила closeContext).
- ASCII-диаграмма порядка хуков обновлена с per-context lifecycle.

Регресс 19/19 ✓ (9m 16.8s).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-13 16:07:45 +03:00
Nick Shirokov 6c19846051 feat(web-test): T4.6 — гибридные режимы изоляции контекстов (tab default, window opt-in)
browser.mjs v1.12 + run.mjs v1.9: createContext принимает isolation параметр.
По умолчанию 'tab' — все контексты живут в одном launchPersistentContext, каждый
слот получает свою Page (вкладку). Преимущества: 1С extension грузится
надёжно (через --load-extension в persistent profile), один процесс Chromium,
дешёвая память. Cookies делятся между вкладками, но скоупятся по URL-path —
для модели «разные пользователи через разные vrd-публикации» это естественно
и достаточно.

isolation: 'window' (opt-in) — старый путь chromium.launch() + newContext():
полная изоляция cookies, отдельный BrowserContext (и окно) на каждый слот,
но extension может не подняться. Использовать когда нужна изоляция auth
внутри одного URL.

Смешивать режимы в одном прогоне нельзя — createContext бросает явную
ошибку (первый createContext устанавливает activeMode, остальные обязаны
совпадать).

Конфиг tests/web-test/webtest.config.mjs: добавлен комментарий с описанием
обоих режимов. По умолчанию tab — синтетика и наши smoke-тесты идут им.

Live: 11/12 в полном прогоне (default tab) + 3/3 sanity-check в window mode
(01-navigation + 14 + 15). Видеозапись из T4.5 работает в обоих режимах.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 18:34:44 +03:00
Nick Shirokov eef4f4bcea feat(web-test): T4.5 — мульти-контекстная запись видео
browser.mjs v1.11: recorder стал глобальным (не per-slot) — один ffmpeg,
один mp4 на тест с любым числом переключений контекста.

Frame state (lastFrameBuf/lastFrameTime/handler) переехал в поля recorder.
Добавлен recorder._attachPage(targetPage) — стопает старый CDP screencast,
заводит новый на нужной странице, route'ит фреймы в тот же ffmpeg pipe.

setActiveContext: при активной записи делает _flushFrames (замораживает
хвост уходящего окна), затем _attachPage(page) после _activateSlot. Видео
получается непрерывным с плавным сюжетом — пока активен a, видно a; пока
активен b, видно b.

_saveActiveSlot/_activateSlot больше не трогают recorder/lastCaptions/
lastRecordingDuration — recorder следует за активной страницей через
_attachPage, не через slot mirror.

disconnect: убрал leftover из T4.1, который пытался итерировать slot.recorder.

Live: 15-multi-context-handover с --record → 17.84s mp4, 446 кадров @ 25fps,
извлечённые кадры показывают переключение между окнами a (1920x1042) и
b (982x546). Полный регресс 11/12 (04-selectvalue — pre-existing flake).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:58:31 +03:00
Nick Shirokov 2c553fee98 feat(web-test): T4 — мульти-контекст BrowserContext
browser.mjs v1.10: createContext/setActiveContext/listContexts/getActiveContext/
hasContext. Несколько изолированных BrowserContext в одном Chromium-процессе через
chromium.launch() + newContext(). Module-level page/sessionPrefix/seanceId/recorder
зеркалят активный слот (атомарный своп через _saveActiveSlot/_activateSlot).
connect() оставлен для exec/run/start без изменений (launchPersistentContext).

run.mjs v1.8: ensureContext(name) + ленивое создание. Single-routing через
export const context = 'name'. Multi через export const contexts = ['a','b'] +
buildScopedContext(name) строит ctx.a/ctx.b — каждое действие префиксится
setActiveContext. Reset state после теста по всем активным контекстам.

Конфиг tests/web-test/webtest.config.mjs: два контекста a/b на одну webtest
публикацию (изолированные cookies через newContext).

Smoke-тесты:
- 14-multi-context-routing.test.mjs — single routing в b (2.6s)
- 15-multi-context-handover.test.mjs — ctx.a создаёт Контрагента, ctx.b в
  независимой сессии видит запись через filterList, ctx.a cleanup (14.5s, 4/4)

Live: 11/12 в полном прогоне. 04-selectvalue/direct-form флапает —
pre-existing, воспроизводится на baseline 95e4674 (03→04 sequence).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-10 17:24:24 +03:00
Nick Shirokov 00fafd4af5 fix(web-test): scanSpreadsheetCells — use contentFrame() instead of index-based frame mapping
Replace fragile page.frames()[iframeIdx + 1] with handle.contentFrame() for
reliable iframe-to-Playwright-Frame resolution. The old index arithmetic could
break when 1C web client accumulates extra frames during prolonged sessions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-16 18:15:05 +03:00
Nick Shirokov afdfc97fb1 fix(web-test): readSpreadsheet — поддержка text-only и отчётов с числовыми шапками
Рефакторинг buildSpreadsheetMapping на 3-уровневый алгоритм.
- Level 1: якорь по DCS-кодам (К1..Кn) — детерминированный для всех ФСД-отчётов, работает независимо от формата чисел (рубли/тыс/млн).
- Level 2: якорь по форматированным числам (пробел-группировка, запятая-десятичка, ведущий минус) вместо общей проверки — голые целые (коды счетов "50", "51") больше не принимаются за данные.
- Level 3: single-row header fallback для text-only данных и query-console.

Починено:
- ФСД-отчёты с числами в групповых шапках (ДДС по счетам 50/51/52/55/57) — был fallback raw rows, теперь структурированный вывод.
- query() из consoleЗапросов для text-only результатов — был data=[], теперь корректно парсит headers/data.

E2E проверено на titan: 4 отчёта (ДС, 45, 77, Ведомость) + 5 query-кейсов. Регрессий нет.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-14 19:38:47 +03:00
Nick Shirokov afacaa5ade fix(web-test): readSpreadsheet header detection for DCS reports with account codes
- Strict isNumericVal check excludes account codes like "68/78" from being
  treated as data values (require pure digits+spaces+commas)
- Require >=2 numeric cells to identify data rows (fallback to >=1)
- Detect DCS column code rows (К1..Кn) and always prefix with group/superRow
- 3-level header support: superRow values used as prefix when group is empty
- superRow excluded from title/meta section
- Fuzzy column matching in clickElement for short codes ("К6" → "84 / К6")
- Replace newlines with spaces in cell text (innerText instead of textContent)

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-08 19:25:37 +03:00
Nick Shirokov 123fc41b06 fix(web-test): selection form search order and type dialog fast path
pickFromSelectionForm: swap steps 2↔3 — try Alt+F advanced search
before search input to avoid overlay blocking row clicks.
pickFromTypeDialog: scan visible rows first, fall back to Ctrl+F
only for large virtual lists. Reduces 3s hardcoded wait to ~0.2s
for common case. scanGridRows: add isGroup flag via gridListH check.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-07 15:43:44 +03:00
Nick Shirokov ae1dcaac07 feat(web-test): detect SpreadsheetDocument state bar (stateText)
Extract info bar messages from .stateWindowSupportSurface elements
into errors.stateText — covers missing parameters, "report not
generated", "settings changed", and "generating..." states.
readSpreadsheet() now includes the state message in its error.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-06 16:27:24 +03:00
Nick Shirokov ffc34904c5 fix(web-test): adaptive header detection threshold for narrow spreadsheets
Hardcoded threshold of 3 non-empty cells prevented header detection in
spreadsheets with 1-2 columns (e.g. query console results). Use
Math.min(3, maxCol + 1) so narrow tables can still be parsed structurally.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 19:19:24 +03:00
Nick Shirokov b008c820f9 fix(web-test): stop group header carry-forward leaking into unrelated columns
When a spreadsheet has 3 header levels (group → detail → codes), the
carry-forward logic for merged group headers would bleed into columns
belonging to different top-level groups. Detect a "super-row" above the
group row and reset carry-forward when a new top-level header starts.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:51:10 +03:00
Nick Shirokov e5697d6f5c fix(web-test): reliable arrow-key scroll for off-screen spreadsheet cells
Rewrites scrollSpreadsheetToCell with fixes for multiple issues discovered
during E2E testing:

- Use Playwright boundingBox (page-level coords) instead of frame-internal
  getBoundingClientRect for visibility checks — frame's clientWidth is wider
  than the actual visible iframe area clipped by parent elements
- Use iframe element's boundingBox to determine visible region — cells behind
  the section panel (x < iframeBox.x) were incorrectly considered "visible"
  and focus clicks hit the section panel instead of the spreadsheet
- Use div[y]+div[x] attribute selectors instead of div.RxCy CSS classes —
  the RxCy class numbering differs from y/x attribute values
- Accept cellLoc parameter from caller instead of re-searching — avoids
  selector mismatch and handles cells missing from some rows
- Native click through mxlCurrBody overlay (page.mouse.click) for focus —
  frame.locator().click() bypasses overlay causing header/data desync,
  page.mouse.click() + frameEl.focus() doesn't transfer keyboard focus
- Pick rightmost/leftmost fully-visible cell for focus based on scroll
  direction — each arrow press immediately triggers platform scroll

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 18:17:04 +03:00
Nick Shirokov 29ee294de6 fix(web-test): arrow-key scroll for off-screen spreadsheet cells (WIP)
Scroll via arrow keys with native platform behavior. Works for
moderate scroll (few columns off-screen). Known limitations:
- Far off-screen columns may timeout
- Re-clicking between direction changes can break scroll context
- Edge cells (first/last column) may not fully scroll into view

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 16:30:18 +03:00
Nick Shirokov d72cbacfd6 fix(web-test): scroll spreadsheet cell into view before clicking
Cells outside the visible iframe area couldn't be clicked because
boundingBox() returned null. Now scrollIntoView() is called first.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 14:45:31 +03:00
Nick Shirokov ea8b28280d feat(web-test): add SpreadsheetDocument cell clicking to clickElement
Extend clickElement to support clicking cells in rendered reports
(SpreadsheetDocument). First argument accepts { row, column } object
where coordinates match readSpreadsheet() output. Text fallback also
searches spreadsheet iframes when element not found in main DOM.

Refactor readSpreadsheet internals into reusable helpers:
scanSpreadsheetCells, buildSpreadsheetMapping.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-04 13:03:05 +03:00
Nick Shirokov 47c2e5d48f fix(web-test): detect textarea forms and normalize Windows paths
Simple EPF forms with textarea fields were invisible to form detection
(formCount: 0) and misclassified as modal error dialogs. Also, backslash
paths in exec scripts caused "Invalid Unicode escape sequence" JS parse errors.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-03 12:31:49 +03:00
Nick Shirokov 84462e3dd9 feat(web-test): highlight command groups on function panel
highlight() now supports command group headers (eAccentColor labels)
on the 1C function panel. Matches group name, collects header +
commands below it, draws multi-element bounding box overlay.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-02 13:27:50 +03:00
Nick Shirokov 09bc0d00b8 fix(web-test): use target.y coordinates to find expand icon row
The expand/collapse code re-searched for the target row by first-cell
text, which was ambiguous when parent and child rows share the same
prefix (e.g. "БУ"). This caused expand to hit the wrong (already-
expanded) row and skip. Use target.y from the initial findClickTarget
instead — matches the exact row.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 14:17:40 +03:00
Nick Shirokov 66c6dc7aa1 fix(web-test): swap gridListH/V in isExpanded — hierarchy expand was inverted
gridListH = collapsed (▶), gridListV = expanded (▼). The old code had it
backwards, so `expand: true` on a collapsed group was a no-op.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-01 13:48:40 +03:00
Nick Shirokov 009022d04b fix(web-test): close DLB hint popup before paste fallback in fillReferenceField
When DLB dropdown shows only a hint ("Введите строку для поиска...") without
.eddText items, the code fell through without closing the popup. This left
editDropDown covering the input field, causing Playwright to wait up to 30s
for actionability on the next page.click(). Now we Escape the hint popup
when eddState.visible=true but items are empty (34s → 5s on cold cache).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-30 20:12:41 +03:00
Nick Shirokov 6c01f3a261 feat(web-test): multi-select rows with modifier + _selected in readTable
Add modifier option ('ctrl'|'shift') to clickElement for Ctrl+click
(add to selection) and Shift+click (select range) in grid rows.
Add _selected: true flag to readTable rows so the model can verify
which rows are currently selected before performing actions.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 15:10:51 +03:00
Nick Shirokov 506f0b84df feat(web-test): clear fields via empty value — Shift+F4 in fillFields, selectValue, fillTableRow
Pass '' or null as value to clear any field (except checkbox/radio) via native 1C Shift+F4.
Returns method: 'clear'. Handles tree grids (close selection form first) and flat grids (dblclick to enter edit mode).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 14:15:52 +03:00
Nick Shirokov f5c02144cb fix(web-test): refine confirmation pause — remove from clickElement, reduce to 500ms in closeForm
clickElement confirmation handling is cleanup of stale dialogs — no pause needed.
closeForm confirmation is intentional user action — keep 500ms pause during recording
(on top of ~600ms from waitForStable = ~1.1s total dialog visibility).

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 12:49:20 +03:00
Nick Shirokov d982c5082a fix(web-test): closeForm — pause before auto-clicking confirmation during recording
Same 1.5s pause as in clickElement for confirmation dialogs when video
recording is active. Applies when closeForm({ save: true/false }) auto-clicks
the confirmation button.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-27 12:39:15 +03:00