Skip to content

feat(extension): Wave 5A zero-tax MV3 runtime injection, orphan window reaping, and shared dom-primitives - #754

Merged
NianJiuZst merged 1 commit into
Tencent:mainfrom
NianJiuZst:feat/wave5a-mv3-runtime-injection
Nov 16, 2026
Merged

NianJiuZst merged 1 commit into
Tencent:mainfrom
NianJiuZst:feat/wave5a-mv3-runtime-injection

Conversation

@NianJiuZst

@NianJiuZst NianJiuZst commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Why (根因与动机)

  1. Zero-tax everyday browsing: Static <all_urls> content_scripts in manifest.json previously forced every ordinary user tab and subframe to load React 19 UI bundles, dispatch WXT wxt:content-script-started window.postMessage broadcasts, or emit startup wakeup IPC, while bh.sessions_live (sessions-live-flag.ts) had decayed into write-only dead code.
  2. MV3 Service Worker crash orphan windows: When an MV3 Service Worker isolate terminated after daemon sessions ended, dedicated Agent Windows created before the termination could remain orphaned on the user's desktop.
  3. Cross-module DOM duplication, self-pollution & runtime injection ordering: Duplicated DOM helpers across cooperation-capture.ts and record-capture.ts left dead Isolated World history.pushState/replaceState monkey-patching, allowed internal data-bsk-* / <browser-skill-overlay> mutations to advance FrameState.structure, risked recording interactions or hover surfaces inside extension ShadowRoot overlays as webpage trace steps, and needed deterministic cooperation.js-before-content.js/record-frame.js ordering plus open/closed ShadowRoot subframe traversal so chrome.tabs.sendMessage never encounters an undefined reply on a live document without cooperation.js.

What (核心改动与解法边界)

  • Zero static manifest.json content_scripts & idempotent runtime entrypoints:
    • Migrated all 4 content script entrypoints (content.ts, cooperation.content.ts, record-frame.content.ts, and long-screenshot-page.content.ts) to WXT registration: "runtime" with noScriptStartedPostMessage: true and claimIdempotentContentScript mount guards (bsk.overlay.mounted, bsk.cooperation.mounted, bsk.record_frame.mounted, bsk.long_screenshot_page.mounted), stripping static content_scripts (and duplicate host_permissions) from dist/chrome-mv3/manifest.json.
  • Tier A on-demand injection (content.js, long-screenshot-page.js) & strict ordering after Tier B:
    • Added per-tabId/documentId idempotent ensureOverlayInjected across controlled task tabs, webNavigation.onCommitted (including Speculation Rules prerender outermost_frames), pre-confirmation tab_borrow candidate user tabs, request_help, record, and active video overlays.
    • Sequenced pushOverlayStateForTab strictly after injectCooperationAllFrames on onAgentTabClaimed, and invoked ensureOverlayInjected from attachCooperation's onOutermostFrameArmed callback after armCommittedFrame settles, ensuring Tier A's onMessage listener is never mounted on a controlled document ahead of cooperation.js.
    • Skipped uninjected tabs on hidden / CAPTURE_SUPPRESS / INPUT_PASSTHROUGH and re-verified ownership after async injection so mid-injection detach/return never flashes stale control UI.
  • Tier B lifecycle coordination, co-injection & Shadow-DOM subframe coalescing (cooperation.js, record-frame.js):
    • Added RuntimeContentScriptCoordinator registering Tier B scripts with persistAcrossSessions: false when liveSessions + activeRecordings > 0 and calling unregisterContentScripts() when counts return to 0.
    • Loaded Tier B silently at document_start with 0 DOM listeners, 0 startup IPC, and 0 window.postMessage noise until armed by Background (COOPERATION_ARM_FRAME / RECORD_FRAME_START) with 50ms per-tab subframe coalescing (COOPERATION_SUBFRAME_READY / subframe_added).
    • Co-injected [cooperation.js, record-frame.js] in injectRecordFrameAllFrames, preserved subframeNeedsInject across scheduleObserveTab debounce resets, pierced open and closed ShadowRoots (openOrClosedShadowRoot) across hasAddedSubframeElement, cooperation-capture.ts, and frame-agent.ts, and probed per-frame COOPERATION_ARM_FRAME via injectCooperationAllFrames across tab_borrow, record_start, COOPERATION_SUBFRAME_READY, ack === undefined frames, and dynamically inserted light-DOM, nested grandchild, or closed-ShadowRoot about:blank / srcdoc / object / embed / fencedframe subframes.
    • Deleted dead apps/extension/src/lib/sessions-live-flag.ts.
  • SW-startup orphan Agent Window reaping:
    • Added OrphanAgentWindowLedger (chrome.storage.session key bsk.orphan_agent_windows) tracking ownedTabIds per dedicated Agent Window and reaping pure orphan Agent Windows on Service Worker restart while strictly preserving any window containing user, borrowed, or human-preserved tabs.
  • Shared apps/extension/src/content/dom-primitives.ts & CI integration:
    • Extracted shared ShadowRoot/overlay/password/mutation/subframe/idempotency primitives into dom-primitives.ts, removed dead Isolated World history.pushState/replaceState patching from record-capture.ts, filtered data-bsk-* and <browser-skill-overlay> mutations in cooperation-capture.ts, excluded extension ShadowRoot UI events and hover surfaces across record-capture.ts, record-hover-surface.ts, and cooperation-capture.ts, updated bilingual CHANGELOG.md / CHANGELOG.zh-CN.md, and wired src/entrypoints/__tests__/runtime-injection.browser.test.ts into .github/workflows/ci.yml.

Adversarial Verification (对抗反例验证)

  1. Counterexample A (Zero-session & bystander isolation + pre-borrow confirmation): Verified getRegisteredContentScripts() === [], 0 <browser-skill-overlay> hosts, 0 window.postMessage noise, and 0 cooperation receivers on ordinary/bystander user tabs before and during active sessions, while on-demand Tier A injection renders the tab borrow Allow modal on the candidate user tab prior to ownership transfer.
  2. Counterexample B (Repeated injection idempotency + dynamic about:blank/srcdoc + Speculation Rules prerender): Verified repeated executeScript of content.js and cooperation.js preserves singleton <browser-skill-overlay> state and every frame's FrameState.document UUID/lease, 50ms debounced COOPERATION_SUBFRAME_READY arms dynamic about:blank and srcdoc iframes, and prerendered outermost_frame retains its overlay across activation.
  3. Counterexample C (Active recording + cooperation coexistence on child, nested grandchild, and closed-ShadowRoot about:blank subframes & overlay isolation): Verified data-bsk-* and overlay mutations do not advance FrameState.structure, dynamic child, nested grandchild, and closed-ShadowRoot about:blank subframes inserted during active bsk record start receive both record-frame.js and cooperation.js without failing cooperation.read on undefined replies, clicks across all 3 dynamic about:blank subframes + main page are recorded into trace.json while ShadowRoot Finish clicks are excluded, and Tier B registrations return to [] after stop.
  4. Orphan Agent Window SW Crash/Restart E2E: Stopped the live MV3 Service Worker V8 isolate mid-session and woke a fresh SW isolate, verifying pure orphan Agent Windows are reaped while mixed Agent Windows containing user-opened tabs are preserved.

Tiered Testing Verification (分层验证记录)

  • Tier 1 (Static & Build Gates):
    • pnpm --filter @browser-skill/extension exec tsc --noEmit
    • pnpm ext:build + verified apps/extension/dist/chrome-mv3/manifest.json has content_scripts === undefined
    • npx biome check across all 34 modified TS/JSON files, npx stylelint "apps/extension/src/**/*.css", python3 scripts/check-changelog-sync.py feb17309
    • cargo fmt --all -- --check, cargo clippy --workspace --all-targets --locked -- -D warnings, node scripts/check-crate-skill.mjs, node scripts/check-skill-bundles.mjs
  • Tier 2 (rg-targeted Unit & Protocol Contract Tests):
    • cargo test -p bsk-protocol --locked (182 passed)
    • pnpm --filter @browser-skill/extension exec vitest run on all 12 rg-matched unit test suites (531 passed across 3 consecutive runs)
  • Tier 3 (Targeted Real Chrome E2E Browser Suites):
    • node scripts/run-browser-tests.mjs src/entrypoints/__tests__/runtime-injection.browser.test.ts src/content/__tests__/cooperation-capture.browser.test.ts (2 suites passed, 0 skipped)
    • node scripts/run-browser-tests.mjs src/cooperation/hidden-frames.browser.test.ts src/content/__tests__/record-input-buttons.browser.test.ts (2 suites / 11 tests passed, 0 skipped)
    • Full heavy workspace/browser matrix deferred to PR CI.

…w reaping, and shared dom-primitives

Why:
1. Static <all_urls> content_scripts in manifest.json forced every ordinary user tab and subframe to load React 19 UI bundles, broadcast WXT content-script-started window.postMessage events, or fire startup wakeup IPC, while bh.sessions_live had decayed into write-only dead code.
2. When an MV3 Service Worker died after daemon sessions ended, dedicated Agent Windows created before the crash could remain orphaned on the user's desktop.
3. Duplicated DOM helpers across cooperation-capture and record-capture left cross-module bugs: dead Isolated World history.pushState patching, data-bsk-* / overlay host mutations advancing FrameState.structure, interactions or hover surfaces inside extension ShadowRoot overlays being mis-recorded as webpage steps, and unsequenced/un-pierced runtime subframe injections risking undefined message replies.

What:
- Migrate all 4 content script entrypoints (content, cooperation.content, record-frame.content, long-screenshot-page.content) to WXT registration: "runtime" with noScriptStartedPostMessage: true and claimIdempotentContentScript mount guards, and strip static content_scripts (and duplicate host_permissions) from dist/chrome-mv3/manifest.json.
- Inject Tier A (content.js and long-screenshot-page.js) per tabId/documentId on demand via idempotent ensureOverlayInjected across controlled task tabs, webNavigation.onCommitted (including Speculation Rules prerender outermost frames, sequenced strictly after Tier B cooperation.js arming/repair), pre-confirmation borrow candidate tabs, request_help, record, and active video overlays; skip uninjected tabs on hidden / CAPTURE_SUPPRESS / INPUT_PASSTHROUGH and re-verify ownership after async injection.
- Coordinate Tier B (cooperation.js and record-frame.js) via RuntimeContentScriptCoordinator with persistAcrossSessions: false when liveSessions or activeRecordings > 0 and unregisterContentScripts() at 0; load silently at document_start with 0 DOM listeners, 0 startup IPC, and 0 window.postMessage noise until armed by Background with 50ms per-tab subframe coalescing; co-inject cooperation.js alongside record-frame.js in injectRecordFrameAllFrames, sequence injectCooperationAllFrames ahead of pushOverlayStateForTab on tab claim, and probe per-frame COOPERATION_ARM_FRAME across tab_borrow, record_start, COOPERATION_SUBFRAME_READY (preserving subframeNeedsInject across debounce resets), ack === undefined frames, and dynamic light-DOM or open/closed ShadowRoot about:blank / srcdoc / object / embed / fencedframe subframes; delete dead sessions-live-flag.ts.
- Track dedicated Agent Window ownedTabIds in chrome.storage.session (bsk.orphan_agent_windows) via OrphanAgentWindowLedger and reap pure orphan Agent Windows on SW startup without closing windows containing user, borrowed, or human-preserved tabs.
- Extract shared apps/extension/src/content/dom-primitives.ts, delete Isolated World history.pushState/replaceState patching in record-capture.ts, filter data-bsk-* and <browser-skill-overlay> mutations from cooperation-capture.ts, exclude extension ShadowRoot UI events and hover surfaces across record-capture.ts, record-hover-surface.ts, and cooperation-capture.ts, and wire runtime-injection.browser.test.ts into CI.
@NianJiuZst
NianJiuZst force-pushed the feat/wave5a-mv3-runtime-injection branch from e2daf41 to 9892196 Compare November 15, 2026 20:56
@NianJiuZst
NianJiuZst merged commit 3b1a23b into Tencent:main Nov 16, 2026
12 checks passed
NianJiuZst added a commit to shunxinyi-ljs/BrowserSkill that referenced this pull request Nov 16, 2026
…ncent#724)

Why:
1. Main advanced past 0.5.0 through Wave 2-5A (Tencent#731-Tencent#754) and Tencent#749, creating
   adjacent [Unreleased] merge conflicts in CHANGELOG.md and CHANGELOG.zh-CN.md.
2. Tencent#731/Tencent#732 unified real-browser suites on BSK_TEST_CHROME and enforced via
   scripts/run-browser-tests.test.mjs that every *.browser.test.ts suite is
   registered in .github/workflows/ci.yml with zero skipped assertions.

What:
- Merge origin/main and place the bilingual Tencent#594/Tencent#724 changelog entries under
  [Unreleased] -> Fixed / 修复.
- Migrate apps/extension/src/content/__tests__/record-editor-value.browser.test.ts
  from legacy BSK_CLICK_CHROME to BSK_TEST_CHROME.
- Register src/content/__tests__/record-editor-value.browser.test.ts in
  .github/workflows/ci.yml alongside record-input-buttons.browser.test.ts.
NianJiuZst added a commit to NianJiuZst/BrowserSkill that referenced this pull request Nov 17, 2026
… cold 2x full-page captures

Why:
- After Wave 5A (Tencent#754) moved `content.js` to lazy runtime injection, cold 2x DPR
  SwiftShader full-page captures (`agent.browser.test.ts` `scale = 2` on 2-vCPU
  Linux CI runners) can overlap initial Tier-A ShadowRoot CSS/React mount and
  `CAPTURE_SUPPRESS` two-frame compositing with `runBrowserMutation` frame
  collection, intermittently exceeding the 1200ms per-frame IPC deadline with
  `FrameUnresponsiveError` (`effect_state: "none"`).
- `guardedRunner.runBrowserMutation` also invoked `beginDomMutation()` followed
  immediately by `prepare()`, issuing two redundant back-to-back full-tab
  `collectCooperationFrames` sweeps per call, while `handleFullPageScreenshot`
  wrapped passive read-only `inspect` probes in `runBrowserMutation`.

What:
- Call `prepare(undefined, "Browser.mutate")` directly in `runBrowserMutation`
  (`action-guard.ts`), preserving full decision/expectation and pending-gesture
  verification in a single frame sweep before `dispatch(true, "Browser.mutate")`.
- Skip `runBrowserMutation` on passive `inspect` probes in
  `handleFullPageScreenshot` (`screenshot-full-page.ts`).
- Raise `FRAME_REPLY_TIMEOUT_MS` (`browser-bridge.ts`) and `OWNER_REPLY_MS`
  (`hidden-frames.ts`) from `1200ms` to `3000ms`.
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