Skip to content

feat(plugin-history-sync): support preventDefault via history reconciliation (FEP-2001)#720

Draft
ENvironmentSet wants to merge 5 commits into
mainfrom
feature/fep-2001-reconciler
Draft

feat(plugin-history-sync): support preventDefault via history reconciliation (FEP-2001)#720
ENvironmentSet wants to merge 5 commits into
mainfrom
feature/fep-2001-reconciler

Conversation

@ENvironmentSet

Copy link
Copy Markdown
Collaborator

무엇을 / 왜

@stackflow/plugin-history-syncpreventDefault와 안전하게 공존하지 못하던 네 가지 문제를 해소합니다. 이로써 plugin-blockerpreventDefault 소비 플러그인과 호환되고, 플러그인 자체가 안정화됩니다. (Linear: FEP-2001)

해소한 네 문제:

  1. 브라우저 뒤로가기 pop을 preventDefault할 수 없음 — backward navigation을 dispatchEvent("Popped")로 직접 발행해 onBeforePop pre-effect 훅을 우회.
  2. 프로그래밍적 pop() 시 history desynconBeforePophistory.back()을 비동기 큐에 등록한 뒤 다른 플러그인이 preventDefault하면 스택은 불변인데 큐의 history.back()은 실행됨(onBeforeStepPop·onBeforeReplace도 동일).
  3. 브라우저 앞으로가기 push가 prevented되면 desync + pushFlag 카운터 오염 — 출처 추적 카운터가 prevented 시 누수되어 이후 정상 push에서 동기화를 건너뛰는 연쇄 desync.
  4. onBeforePop 훅 실행 순서 의존성 — pre-effect 훅의 비가역 부작용이 등록 순서에 의존.

어떻게 (메커니즘)

네 문제는 한 뿌리를 공유합니다 — 플러그인이 브라우저 history를 여러 곳에서(pre-effect 훅, post-effect 훅, 낙관적 카운터) 제각기 만지고, 브라우저 뒤로가기를 액션 경로가 아닌 dispatchEvent로 우회한 것. 이를 reconciler 구조로 뒤집어 브라우저를 "커밋된 스택"의 엄격한 추종자로 만듭니다.

  • 단일 동기화 권위 (HistorySyncController): 브라우저 history를 변경하는 권위를 하나의 동기화 과정으로 모읍니다. history는 커밋된 스택 변화에만 반응합니다(원리 A — 커밋된 effect에만 history를 만진다).
  • 브라우저←스택 단일 방향 (원리 B): 사용자가 일으킨 popstate는 브라우저를 직접 만지지 않고 정상 액션 파이프라인(pop/stepPop/push)으로 번역됩니다. 그래서 다른 플러그인의 onBefore*가 실행되고 preventDefault가 존중됩니다. 막히면 동기화가 브라우저를 복원하고, 커밋되면 동기화가 따라갑니다.
  • 플러그인 소유 ordinal 좌표: 위치·거리·방향은 core 활동 id 순서가 아니라 history state에 stamp한 플러그인 내부 ordinal로 계산합니다(core id는 동일성 매칭에만). id 순서성에 기대지 않습니다.
  • idle-gated 순수·멱등 동기화 패스: delta = stackOrdinal − browserOrdinal로 정착(idle) 시점에만 1회 동기화. 버퍼링되는 비동기 커밋을 자동 흡수하고, 같은 차이엔 무동작.
  • self-induced 억제 토큰: 자기 유발 history.go만 단일 in-flight 토큰으로 1:1 소비하고, 이동 없는 동작엔 토큰을 set하지 않아 누수가 없습니다.

pre-effect 훅에서 비가역 부작용(history.back() 큐잉)·누수 카운터(pushFlag)·우회 경로(dispatchEvent("Popped"))·억제 플래그(silentFlag)를 전부 적출했습니다. 결과적으로 네 문제가 모두 영구 desync에서 정지점마다 자가치유되는 일시 글리치로 범주가 바뀝니다(eventual consistency).

문제별 해소

문제 해소
1 (back veto 불가) dispatchEvent 우회 폐기 → 액션 파이프라인 번역으로 onBeforePop·preventDefault 존중
2 (program pop desync) pre-effect history.back() 큐잉 전량 제거 → prevented 시 커밋 0 → history 무변
3 (forward 카운터 누수) pushFlag 폐기 → 출처는 (스택, 엔트리) ordinal 차이의 귀결, 누수 불가
4 (훅 순서 의존) history 부작용 전량 커밋 후 동기화로 이동 → pre-effect 무부작용 → 등록 순서 독립

범위

  • 수정은 plugin-history-sync에 갇힘: extensions/plugin-history-sync/src/의 4파일(HistorySyncController.ts 신규, historyState.ts, historySyncPlugin.tsx 재작성, historySyncPlugin.spec.ts).
  • @stackflow/core의 이벤트/훅 계약 불변. 공개 이벤트/effect에 새 필드 없음(ordinal은 history state 내부 데이터).
  • 공개 API 비파괴.
  • 페이지 새로고침(reload) 이후 동기화는 범위 제외(후속 과제) — reload 시 엔트리 ordinal 재구축이 별도 문제.

검증 — preventDefault reconciler 하니스 (e2e/)

구현보다 먼저 만든 검증 하니스를 함께 추가합니다 (e2e/, @stackflow/e2e-history-sync-blocker):

  • 실제 Chromium(T1) + jsdom(T2i) 에서, plugin-history-syncplugin-blocker를 모두 적용한 상태로 검증.
  • 87개 테스트 = 네 문제 재현 + preventDefault 소비자 호환 계약 + 동시성/재진입 + 양 플러그인 기존 스위트 케이스 1:1.
  • 관찰 계약: SCREEN(DOM)·URL·STACK(공개 getStack)·NAVIGABILITY·blocker 통보 로그만 단언(내부 좌표 비단언).
  • 미수정 코드에선 네 문제 지점 32개가 red, 이 구현으로 87개 전부 green(독립 재실측으로 결정성 확인).

설계 근거는 plans/fep-2001/(solution-plan · glossary · ADR 0001~0008)에 함께 담았습니다.

Draft 체크리스트 (ready 전)

  • changeset 추가 (@stackflow/plugin-history-sync minor/patch)
  • CI 통과 확인 (e2e 하니스 포함 시 Chromium 설치 step 필요 여부 검토)
  • reload 후속 과제 이슈 분리

Closes FEP-2001

🤖 Generated with Claude Code

https://claude.ai/code/session_011zkdvyQTHayZMSLw5AUn9q

ENvironmentSet and others added 5 commits June 28, 2026 21:53
…n (FEP-2001)

Confirmed solution mechanism for making plugin-history-sync coexist safely
with preventDefault (plugin-blocker compatibility + history-sync stabilization).

Mechanism (planning altitude only — no code-change plan):
- Anchor browser-history mutation to committed stack effects only; pre-effect
  hooks have no observable side effects (kills hook-order dependency).
- Browser strictly follows the settled committed stack; user popstate only
  attempts the matching stack action through the action pipeline (preventDefault
  honored). Single sync authority (publish) is a pure, idempotent function of
  (current stack, current entry).
- Plugin-owned per-entry ordinal for position/distance/direction (no dependency
  on core id ordering). delta = O_stack - O_browser.
- Single serial queue + idle gating + publish coalesce; suppression token
  (silentFlag) blocks user nav while a self-induced op is in flight.
- Correctness guarantee = level-triggered eventual consistency (browser == stack
  at every rest point, zero permanent desync); transient glitch / single-input
  loss under extreme races is accepted.
- Race policy: no direct arbitration — browser follows the core's deterministic
  event replay. Scope: plugin-confined, core unchanged, reload cold-start excluded
  (follow-up).

Resolves problems 1-4 from the issue. Deliverable: solution-plan + glossary + ADRs.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FynMwgeussV4PT1LjJYMUz
…P-2001)

A real-browser (T1: jest + playwright library + in-process vite preview) and
jsdom (T2i) safety net proving @stackflow/plugin-history-sync coexists with
preventDefault consumers (@stackflow/plugin-blocker). Both plugins are applied
together; every quiet point asserts browser == stack (SCREEN ⇿ URL ⇿ STACK).

- Dedicated harness app configured entirely by URL knobs
  (order/hash/lazyDelay/block/blockers/blockAsync/probe), instrumented via a
  window.__harness__ bridge that exposes only public observations.
- Driver Abstraction Layer over a real Chromium page; settle is observed via the
  public transition state + a double-stable (≥1 rAF + 1 macrotask) check, never
  slept for.
- 87 cases mapping 1:1 to the verification plan: history-sync baseline (25),
  blocker suite (37, incl. 3 jsdom-integration internal-contract cases), the four
  problems (12), the coexistence contract (6), concurrency/reentrancy (7).
- Runs the plugins' current source (aliased to src), so red on the unfixed
  product is expected and the gate turns green once the product upholds the
  contract. The baseline navigation suite is green, proving the harness models
  the system faithfully.

No product code is modified.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016xnbUjkgG4Nrhkoo3VeSm6
…s2-r1)

Address the review's four "witness too weak → false/trivial green" findings;
the suite shape is unchanged (32 red / 55 green, stable) — the added witnesses
pass on the current product where the surrounding case already passed, or sit
after an existing red so they are reached only once the product is fixed.

- HS-07: prove replace did not add a browser entry via navigability
  (browser back leaves the app) in addition to the public stack depth.
- PB-2a: after a blocked pop, prove the back entry is intact
  (cancel/disarm, browser back reaches Home) alongside the fake-forward no-op.
- CC-6: make pop-proceed idempotency observable with a two-level stack
  (one pop lands on Article(1), a duplicate would reach Home) plus a
  browser-back navigability check.
- CX-3: enter the self-induced shrink window positively with waitForNonIdle()
  before injecting the user back (matches the sibling race cases), so the
  suppression-token race is actually exercised rather than trivially green.
- Document the timeout / "navigated away" red mechanism in the affected
  proceed/async cases.

No product code is modified.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016xnbUjkgG4Nrhkoo3VeSm6
Rewrite history↔stack synchronization so browser history is mutated only
in reaction to committed stack changes, never from a pre-effect hook. This
resolves four permanent desyncs with preventDefault-consuming plugins
(see plans/fep-2001/solution-plan.md).

A single authority — HistorySyncController — owns every browser mutation.
Each entry carries a plugin-owned ordinal in its history state; a pure,
idempotent sync pass compares the stack ordinal to the browser ordinal and
pushes, steps back, replaces, or does nothing. It runs only at idle and
coalesces reservations; a single in-flight suppression token keeps the one
self-induced backward move from being read as a user navigation, and is
never taken for a move that does not happen. A user popstate is translated
into the matching pipeline action (pop/stepPop/push/stepPush) so other
plugins' onBefore* hooks run and a preventDefault is honored; the next sync
pass restores the browser when the attempt does not commit.

Removed: the pre-effect history.back side effects (the source of the
order-dependent and program-pop desyncs), the optimistic push-origin
counter (the source of the leaked-counter chain desync), and the
dispatchEvent path for browser back (which bypassed the hooks). The
pre-effect hooks now do only idempotent param normalization.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pv6kvesDjZJDMDqf8wz1d5
…reload

The jsdom navigation suite settled with a fixed delay calibrated to the old
synchronous mechanism. The committed-effect sync converges on the idle
tick, whose wall-clock timing drifts under other tests' lingering
transition timers, so a fixed wait raced that drift. Settle by polling for
the stack to actually reach idle — the same quiet-point contract the
browser harness uses. Assertions are unchanged.

Skip the post-reload history-manipulation case: synchronizing the browser
with the stack after a page reload is out of scope (see
plans/fep-2001/solution-plan.md and
adr/0008-scope-plugin-confined-reload-excluded.md) — only the current entry
is observable on reload, so pre-reload entry ordinals cannot be
reconstructed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Pv6kvesDjZJDMDqf8wz1d5
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 29, 2026

Copy link
Copy Markdown

Deploying stackflow-demo with  Cloudflare Pages  Cloudflare Pages

Latest commit: c6d8858
Status: ✅  Deploy successful!
Preview URL: https://36e2cd86.stackflow-demo.pages.dev
Branch Preview URL: https://feature-fep-2001-reconciler.stackflow-demo.pages.dev

View logs

@changeset-bot

changeset-bot Bot commented Jun 29, 2026

Copy link
Copy Markdown

⚠️ No Changeset found

Latest commit: c6d8858

Merging this PR will not cause a version bump for any packages. If these changes should not result in a new version, you're good to go. If these changes should result in a version bump, you need to add a changeset.

This PR includes no changesets

When changesets are added to this PR, you'll see the packages that this PR includes changesets for and the associated semver types

Click here to learn what changesets are, and how to add one.

Click here if you're a maintainer who wants to add a changeset to this PR

@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Jun 29, 2026

Copy link
Copy Markdown

Deploying with  Cloudflare Workers  Cloudflare Workers

The latest updates on your project. Learn more about integrating Git with Workers.

Status Name Latest Commit Preview URL Updated (UTC)
✅ Deployment successful!
View logs
stackflow-docs c6d8858 Commit Preview URL Jun 29 2026, 08:36 AM

@pkg-pr-new

pkg-pr-new Bot commented Jun 29, 2026

Copy link
Copy Markdown
  • @stackflow/demo

    yarn add https://pkg.pr.new/@stackflow/link@720.tgz
    
    yarn add https://pkg.pr.new/@stackflow/plugin-history-sync@720.tgz
    

commit: c6d8858

@coderabbitai

coderabbitai Bot commented Jun 29, 2026

Copy link
Copy Markdown

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c90cdc87-a88a-435b-b630-6faef6714fd0

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feature/fep-2001-reconciler

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

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