Skip to content

feat(widget): keep state when a host replaces the element - #383

Merged
sydevs-bot merged 7 commits into
mainfrom
claude/feat-349-keep-state
Nov 11, 2026
Merged

sydevs-bot merged 7 commits into
mainfrom
claude/feat-349-keep-state

Conversation

@sydevs-bot

@sydevs-bot sydevs-bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • A host that destroys <sahaj-atlas> and creates a new one under the same key now keeps the query cache and the API key, so a Wix Back/Forward press costs no SahajCloud reads. Measured in a browser: 5 reads before, 0 after.
  • docs/embedding.md gains the Install-tab pointer, a Wix Custom Element section, the remove-before-insert rule, and what a replacement does and does not carry across.

Change outline

Behaviour — connectedCallback, when an element arrives inside the teardown grace window

The release exists so an element re-added under a different key cannot read the first key's responses out of the cache. That reason is now the condition.

 connectedCallback()                                        src/Widget.tsx
   pendingTeardown set?                                     # something left < TEARDOWN_GRACE_MS ago
     clearTimeout; pendingTeardown = null
-    owner !== this                    → releaseOwnership() # clears queryClient, nulls apiKey
+    owner !== this && key changed     → releaseOwnership()
+    owner !== this && key unchanged   → fall through       # the transfer: the cache stays
     owner === this                    → fall through       # a move, as before
   owner && owner !== this && owner.isConnected → refuse, warn, render nothing
   owner = this
   adoptStyles(shadowRoot); super.connectedCallback()       # unchanged

The key compared is atlasAuth.apiKey against embed.config.key: the first is the credential in force and so the cache's lineage, the second is what the arriving element would authenticate as. releaseOwnership moves both together, which is what makes the comparison sound.

Contract — docs/embedding.md

One rule per line, paraphrased.

+§ intro: start from the Install tab on your client record, not from this page
 § The two embed codes
+  § On Wix, the script embed is a Custom Element
+    Server URL `https://sahajatlas.com/auto.js?key=YOUR_KEY`, tag name `sahaj-atlas`
+    not Embed HTML and not an HTML iframe element — Wix frames both off its own origin
+    needs Wix Premium and a connected domain; without them, the iframe embed
+    search listings need the Velo router the Install tab generates; no `routing=path`
+  § If your page replaces the element
+    remove the old element before inserting the new one, or the page is left with none
+    same `key`, within a second → the widget keeps what it had already read
+    a different `key` → drops everything read under the first
+    a page builder relocating the element is the same element, already covered
+    open panels, in-widget Back history and a part-filled form all come back
 § Sizing the element                                       # unchanged; the Wix section links here

Preview

Nothing here is visible by opening a page. The change only shows when an element is replaced, so the reproduction below is the preview — it runs against any embed page, including production.

Paste this in the console on any page carrying the embed, once data-sahaj-atlas-ready is on <html>:

Reproduction
const seen = []
const open = XMLHttpRequest.prototype.open
const fetched = window.fetch
window.fetch = (...a) => (seen.push(String(a[0])), fetched(...a))

document.querySelector('sahaj-atlas').replaceWith(document.createElement('sahaj-atlas'))

// after a second or two:
seen.filter((u) => u.includes('cloud.sydevelopers.com/api/'))
// [] on this branch; five entries on main

The widget's content should reappear at the same route. On main the same snippet lists clients/me, events/geojson, regions, globals/sy-atlas-config and globals/sy-atlas-translations.

Test results

  • Lean gate: ✓ .claude/skills/pr-prep/check.sh — lint, typecheck, 2000 tests in 166 files
  • Targeted specs: 3 passed (src/Widget.replace.test.tsx), each watched red against its own defect — see Detail
  • Build: ✓ pnpm build (incl. assert:css, assert:maps) and pnpm size (embed 329.2 / 330 KiB, unchanged)

Manual verification

Two things no lane here reaches.

  1. The real Wix Custom Element, on https://sydevelopers.wixsite.com/atlas-spike-classic/about with this PR's preview auto.js. The spike site is free, so the Custom Element itself cannot be exercised there — the ticket already schedules this for sahajayoga.ca's go-live.
  2. The Mapbox map instance. No VITE_MAPBOX_ACCESSTOKEN reaches a routine's checkout, so the map never loaded here and I could not measure it. Read off the installed source instead: reuseMaps is already set on <ReactMapGL> (src/components/organisms/Mapbox/Map.tsx), so react-map-gl recycle()s the map into a module-level pool on unmount and Mapbox.reuse() reparents its canvas into the next container — whichever root that is. So the ticket's second bullet needed no code. Worth confirming in a browser that no second map load is billed.

The data half is measured. Against the built embed in Chromium (pnpm review:embed), with the five reads stubbed, replacing the element:

reads caused by the swap
main 5 — clients/me, events/geojson, regions, sy-atlas-config, sy-atlas-translations
this branch 0, and the content comes back

Notes for reviewer

  • The host-facing "what is lost" paragraph was wrong, and is corrected. It listed open panels, in-widget Back history and a half-filled registration. All three come back: resolveStack (lib/shape/path.ts) derives the drawer stack from the pathname, atlas-history.ts reads the depth back out of the browser's own history.state, and useRegistrationDraft is a module singleton releaseOwnership never touches, re-seeded by event id in RegistrationForm.tsx. What a replacement really costs is the old element's React state — a scrolled list starts at the top. CHANGELOG.md carried the same sentence and is corrected with it.
  • Remove before insert is now stated, in the guide and in the owner docblock. The opposite order does not cost one render: the arrival is refused while the old owner still stands, never gets a second connectedCallback, and the old owner's deferred teardown then leaves the page with no widget at all. replaceWith and a framework re-render both remove first.
  • atlasAuth.apiKey, not a new ownerKey. The review pass suggested a second module variable holding the key ownership was taken under. Declined: atlasAuth.apiKey already is that fact — AtlasBoot claims it and releaseOwnership nulls it, in the same pair of functions that own owner — so a second copy would be one more invariant two call sites must keep true. The two differ only before AtlasBoot's first render, where the cache is empty and the outcome is the same either way.
  • Not keying every query by the API key, which would make the cache self-scoping and reduce the release to nulling the credential. It is the deeper fix and much larger, in the repo's most drift-prone place: every factory in config/api/index.ts plus every cache-only reader and writer, and that class of change already shipped silently broken once (live preview wrote ['region', slug] while the drawer read ['region', slug, locale]). The accepted limit and its upgrade trigger are now a shortcut: line beside the condition.
  • A QueryClient per element was considered and is the opposite of the fix — it would die with the element on every Back press.
  • owner.isConnected quietly became load-bearing. Before, a different element always hit the release first, which nulled owner, so the duplicate guard below exited on its first term. Now that guard is the only thing separating a replacement from a second embed, which also makes removal-before-insertion part of the design. The owner docblock says both.
  • One per-edit cost accepted. The new spec's vi.mock('@/styles/sheet', …) quotes a module it never loads, which buys that module a spec selection: editing src/styles/sheet.ts goes 1.15 s → 2.85 s. The mock is needed because jsdom gives a fresh shadow root no adoptedStyleSheets. Editing src/Widget.tsx is 3.3 s at 7 specs, and the widest selection in the tree is unchanged at 20, so docs/testing.md's 12-second budget and its ceiling both hold.
  • Security review: no finding. It ran on the first push because src/Widget.tsx matches securityReview.triggerPattern. It checked whether the transfer can serve key-A data under key B (it cannot — boot is unreachable from host script, and the cache's lineage is the credential the release nulls), every reachable null-key state, and whether skipping releaseAnnouncement leaves a false attestation (the marker disclaims forgery resistance by its own contract, and every mount republishes it). Everything pushed since is comments and Markdown — comment-fingerprint.mjs reports the code hash unchanged.
Detail

The browser measurement. pnpm build && pnpm review:embed, then Chromium against /__review/sidebar-mapless.html with clients/me, events/geojson, regions, sy-atlas-config and sy-atlas-translations fulfilled, waiting for the shadow root, then old.replaceWith(document.createElement('sahaj-atlas')). Run twice: once on this branch, once with the condition reverted to owner !== this and rebuilt. The script is throwaway and is not in the diff.

The three spec cases, and the defect each one caught. docs/testing.md requires watching a new assertion fail at the site that causes it, so each was run against a separate injected defect, before and again after the comment pass:

Case Red against
keeps the cache under the same key owner !== this alone — the behaviour on main
releases under a different key the condition forced false — transfer always
still releases when nothing comes back disconnectedCallback not scheduling the teardown

Why the spec drives the real custom element. The decision is a lifecycle callback, so renderToStaticMarkup reaches none of it. jsdom per docs/testing.md's opt-in. @/App is stubbed so the data layer never boots, which holds the file at 69 ms of test time.

Declined, with the reviewer's own reason. The vi.mock('@/App') factory and the rejecting fetch stub are byte-identical to src/Widget.path-boot.test.tsx's. Two copies is below this repo's extraction threshold, src/test-support/ holds no mount helper, and vitest.config.ts declares no setupFiles, so a per-file local helper is the established convention (Widget.theme-root.test.tsx, sheet.adopt.test.ts).

Also declined: pendingTeardown = null beside clearTimeout is redundant only on the branch that calls releaseOwnership; on the transfer branch it is the only thing that clears it, and hoisting it is what let the old else go — one branch where there were two.

Blocker. sydevs/SahajCloud#1055 closed with sydevs/SahajCloud#1058, so the Install tab the guide points at is live. The pointer names /admin and the tab rather than a deep link, since the record id is per client.

Closes #349

A Wix router page re-renders on Back/Forward, destroying `<sahaj-atlas>` and
creating another element carrying the same configuration. `connectedCallback`
read that as a different element arriving inside the teardown grace window and
ran the release, which clears the query cache and the API key — so every press
cost a full re-read of the feed, the region tree and the client record.

The release exists for one reason, stated at `TEARDOWN_GRACE_MS`: only
`['client', apiKey]` carries the credential in its key, so an element re-added
under a DIFFERENT key would read the first key's responses out of the cache.
That reason is the condition now. Under the same key ownership transfers and
the cache stays; a different key keeps today's release.

The Mapbox instance needed no work: `reuseMaps` is already set on
`<ReactMapGL>`, and react-map-gl recycles the map on unmount and reparents its
canvas into the next container, whichever root that is.

`docs/embedding.md` gains the pointer to SahajCloud's Install tab, the Wix
Custom Element track, and what does and does not survive a replacement.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
…makes

Three restatements the reuse pass found. The Wix section re-argued why a
sandboxed frame costs the shareable, indexable route, which "Which one, and
what you give up" already owns, and re-stated the height rule the Sizing
section owns — both now link instead. The changelog entry re-derived #149's
behaviour from scratch, so a host could not tell what #349 changed; it names
the delta against #149 now.

A factual slip went with them: a page builder relocating the element is the
SAME element coming back, which #149 already covered. Only a re-render puts a
new element in its place.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
The review pass found a six-line block that restated the
`TEARDOWN_GRACE_MS` docblock thirty lines above it and then narrated what
the old behaviour cost. What stays is the part a reader cannot re-derive:
why a new element and not only a returning one, what `owner !== this` buys
once the key comparison is there, and a `shortcut:` line naming the limit
this fix accepts — the cache is key-agnostic bar `['client', apiKey]` — with
the trigger for lifting it.

The ownership rule gained a term silently: `owner.isConnected` is now the
only thing separating a replacement from a second embed on the page, which
also makes removal-before-insertion part of the design. The `owner` docblock
says both.

In the spec, `vi.runOnlyPendingTimers()` replaces a 5s constant that would
have stopped exceeding the grace window if it ever grew.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjVCYjgUifyqdH1rrEQ
@sydevs-bot

sydevs-bot commented Nov 10, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 no session running
CI fix 1

recent dispatches
  • 18:04Z address-review · attempt 1 · session · done
  • 18:04Z address-review · attempt 1 · session
  • 17:56Z review-pr · attempt 1 · session · done
  • 17:56Z review-pr · attempt 1 · session
  • 18:58Z fix-ci · attempt 1 · session · done

Written by the sydevs dispatcher. Sessions never edit this comment.

@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 10, 2026
@cloudflare-workers-and-pages

cloudflare-workers-and-pages Bot commented Nov 10, 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 Updated (UTC)
✅ Deployment successful!
View logs
sahajatlas-design 1ca56c8 Nov 11 2026, 06:12 PM

@sydevs-bot

Copy link
Copy Markdown
Contributor Author

🩹 Smoke is red on a credential, not on this diff. No push fixes it.

wrangler versions upload --preview-alias pr-383 never reached Cloudflare:

A request to the Cloudflare API (/accounts) failed.
  Invalid access token [code: 9109]

/accounts carries no account id, so CLOUDFLARE_API_TOKEN itself is invalid.

It went bad between 18:01Z and 18:29Z today. Green on main in the 18:01Z merge queue. Then 9109 here at 18:29Z, and again on #384 at 18:42Z — a contracts re-sync touching no widget code, workflow or wrangler config. This blocks every pull request in the repo.

A re-run repeats the upload and fails the same way. Someone has to mint a Workers-scoped token and reset the secret.

Nothing on this branch changes. It is level with main, and its other two required checks are green.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 10, 2026
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 10, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 11, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Working in SYDevelopers Technical Roadmap Nov 11, 2026

@sydevs-bot sydevs-bot left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

🧐 Adversarial review

The diff is smaller than the ticket and does the job: one condition in connectedCallback, no new file, helper, constant or dependency, and the deeper fix declined with a shortcut: that names its trigger. Scope matches #349 — the CHANGELOG and the guide were both asked for, and the map half correctly turned out to need no code. The cross-repo claim holds: SahajCloud's Install tab exists (Clients.ts:481), and its Wix templates agree with the guide on Server URL, tag name, Premium plus domain, and the Velo router.

What this review does not accept is the new contract paragraph. The guide tells hosts three things do not survive a replacement, and all three appear to: the drawer stack is the URL, and the zustand stores are module singletons releaseOwnership never touches. That is host-facing copy, so settle it before the reviewer reads it.

Findings

  • should-fix — docs/embedding.md:145: the "what does not survive" list is wrong on all three items.
  • consider — src/Widget.tsx:505: insertion before removal costs the whole widget, not one render.

What was checked

Ticket #349 and parent #348. The diff from the checkout. Read whole: Widget.tsx, config/embed.ts, config/api/auth.ts, config/store.ts, lib/shape/path.ts, lib/shape/navigation.ts, lib/atlas-history.ts, RegistrationForm.tsx, the new spec, both guide sections. Ladder: the diff adds no new piece to walk. Consumer side: SahajCloud InstallGuide/{steps,templates}.ts and Clients.ts against the Wix section; both CHANGELOG anchors resolve. The preview answers 200 now — Smoke went green on this head at 17:56, so the body's "does not resolve yet" line is stale rather than wrong.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

Comment thread docs/embedding.md Resolved
Comment thread src/Widget.tsx Resolved
@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 11, 2026
@sydevs-bot sydevs-bot moved this from Working to Pending in SYDevelopers Technical Roadmap Nov 11, 2026
@sydevs-bot sydevs-bot added the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 11, 2026
@sydevs-bot sydevs-bot moved this from Pending to Working in SYDevelopers Technical Roadmap Nov 11, 2026
sydevs-bot and others added 4 commits November 11, 2026 18:07
The guide told hosts three things are lost on a replacement, and all three
come back. The drawer stack is a pure function of the pathname
(`resolveStack`), the in-widget back depth is stamped into the browser's own
history entry (`atlas-history`), and the registration draft is a module
singleton the release never touches, re-seeded by event id.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYrLvFd4922qDe5641
The docblock called the opposite order one lost render. It costs the page its
whole widget: the arrival is refused while the old owner still stands, it gets
no second connectedCallback, and the old owner's deferred teardown then leaves
nothing running. Hosts need the ordering rule too, so the guide carries it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjYrLvFd4922qDe5641
@sydevs-bot

Copy link
Copy Markdown
Contributor Author

Both review threads adopted and resolved. Pushed as 1ca56c8.

CHANGELOG.md carried the first sentence too, corrected in 1ca56c8. origin/main merged in clean.

Lean gate green: lint, typecheck, 2000 tests in 166 files. No code changed since the security review — comment-fingerprint.mjs reports the same code hash.

Body refreshed: the contract outline, and the preview link, which answers 200 now.

🤖 Written by the sydevs autonomous loop — see what this is


Generated by Claude Code

@sydevs-bot sydevs-bot removed the bot:working Lock: a cloud session is running on this item. Removed when it ends. label Nov 11, 2026
@sydevs-bot
sydevs-bot marked this pull request as ready for review November 11, 2026 18:14
@sydevs-bot
sydevs-bot requested a review from Ardnived November 11, 2026 18:14
@sydevs-bot
sydevs-bot enabled auto-merge November 11, 2026 18:14
@sydevs-bot sydevs-bot moved this from Working to Awaiting in SYDevelopers Technical Roadmap Nov 11, 2026
@sydevs-bot
sydevs-bot added this pull request to the merge queue Nov 11, 2026
@sydevs-bot sydevs-bot moved this from Awaiting to Pending in SYDevelopers Technical Roadmap Nov 11, 2026
Merged via the queue into main with commit 9d50571 Nov 11, 2026
51 of 53 checks passed
@sydevs-bot
sydevs-bot deleted the claude/feat-349-keep-state branch November 11, 2026 18:29
@sydevs-bot sydevs-bot moved this from Pending to Done in SYDevelopers Technical Roadmap Nov 11, 2026
sydevs-bot added a commit that referenced this pull request Nov 11, 2026
#383 and this branch each added an entry at the head of CHANGELOG's
Unreleased § Changed, so git saw an add/add there. Both entries stay,
#392 above #349, which keeps the section newest-first.

Nothing else overlapped: `docs/embedding.md` and `docs/testing.md` took
both sides' new sections cleanly, and the code main brought touches
`Widget.tsx`, which this branch never opens.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Mg9rjZVTLRdTmG2ijYEpfj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

Development

Successfully merging this pull request may close these issues.

feat(widget): keep state when a host replaces the element

3 participants