Repository navigation
feat(core): move recommendation session start to CMS Global Section - #3414
Conversation
WalkthroughRecommendationShelf now uses a per-component CMS opt-in instead of the global experimental flag. Page props determine whether the personalization session starts, with cookie and in-memory safeguards preventing duplicate requests. Schemas, tests, and documentation were updated accordingly. ChangesRecommendation opt-in flow
Estimated code review effort: 3 (Moderate) | ~25 minutes Possibly related PRs
Suggested labels: Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Warning There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure. 🔧 Checkov (3.3.8)packages/core/cms/faststore/schema.jsonTraceback (most recent call last): 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. Comment |
|
This pull request is automatically built and testable in CodeSandbox. To see build info of the built libraries, click here or the icon next to each commit SHA. |
@faststore/api
@faststore/cli
@faststore/components
@faststore/core
@faststore/diagnostics
@faststore/lighthouse
@faststore/sdk
@faststore/ui
commit: |
Enable Recommendations opt-in via CMS by adding StartRecommendationSession to Global Sections, removing the experimental.enableRecommendations flag and Layout wiring so merchants can set up shelves without code changes.
a69db55 to
8589056
Compare
There was a problem hiding this comment.
I don't think we should create a brand-new session without props just to handle the enable/disable of this Shelf. What about using a Boolean prop in the already existing RecommendationShelf session?
renatomaurovtex
left a comment
There was a problem hiding this comment.
Follow-up to the RecommendationShelf work (#3403): graduates the experimental.enableRecommendations flag into a CMS Start Recommendation Session Global Section so merchants opt in without touching store code. Reviewed the full diff against the core package boundaries and the CMS-artifact conventions.
The design holds up: with StartRecommendationSession absent from Global Sections, no startRecommendationSession mutation runs → no vtex-rec-user-id cookie → getRecommendationArguments() returns null → the shelf never fetches. So the CMS opt-in fully replaces the old flag gate. Nice clean-up.
Hygiene checks (all good):
schema.json/sections.jsonare consistent with the new.jsoncsource (identicalStartRecommendationSessionblock) — these are the checked-in CMS artifacts uploaded viavtex content upload-schema, not a__generated__violation.- Flag removal is complete: a repo-wide search for
enableRecommendationsondevreturns only the 6 files this PR edits → zero dangling references after merge. - The two removed tests were asserting the now-deleted flag path, not skipped to make the build pass — legitimate. New
StartRecommendationSessioncomponent test added. ✅ feat(core):title + scope valid; dynamic import with{ ssr: false }mirrorsRecommendationShelfregistration. ✅
💬 [behavior] Removing the section doesn't disable for returning users immediately
The "remove Start Recommendation Session → shelf stops" test step is only true for new browser sessions. A returning visitor who already holds a vtex-rec-user-id (and vtex-rec-user-start-session) cookie from an earlier visit will keep resolving a userId, so the shelf can keep fetching until those cookies expire. Worth a line under Runtime behavior / Troubleshooting so operators aren't surprised.
💬 [test] No direct coverage of the new opt-in invariant
With the flag gone, the load-bearing guarantee is now "no userId → getRecommendationArguments returns null → no fetch". useRecommendationUserId is mocked to 'user-1' in beforeEach, so nothing exercises the missing-id path anymore. Consider one case with useRecommendationUserId.mockReturnValue(undefined) asserting useRecommendations gets null.
💬 [config] Flag graduation
Confirmed experimental.enableRecommendations is not present on main, so it never shipped in a stable (latest) release — no migration note needed. The experimental.* namespace also signals no stability guarantee, so dropping it in dev is fine.
Verdict: Approved with comments
Blocking (🔴/🟠):
- None.
Non-blocking (💬):
- Returning-user cookies keep the shelf fetching after the section is removed (until cookie expiry) — document it.
- Add a test for the
userId-missing → no-fetch invariant. - Confirmed flag was dev-only; no stable migration note required.
Checks to confirm before merge: pnpm lint · build · pnpm vitest run on the touched core tests · pnpm size (core). CI is green here; UI Tests are pending Chromatic baseline acceptance (46 stories) — accept if the storybook diffs are expected.
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts (1)
84-114: 🩺 Stability & Availability | 🟠 Major | ⚡ Quick winRelease the lock when all session-start retries fail.
If every attempt returns
undefinedor the retry rejects,hasRequestedStartRecommendationSessionstaystruewithout a cookie. The session can then never start during this browser runtime, even after the endpoint recovers.Proposed fix
- ).catch(() => {}) + ) + .then((result) => { + if (result === undefined) { + hasRequestedStartRecommendationSession = false + } + }) + .catch(() => { + hasRequestedStartRecommendationSession = false + })🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts` around lines 84 - 114, Update the retry flow in the start-session logic so hasRequestedStartRecommendationSession is reset to false when retry exhausts without a defined result or the retry promise rejects. Keep the lock set after a successful runStartRecommendationSessionRef.current call, ensuring later attempts remain suppressed only when a session was actually started.
🧹 Nitpick comments (1)
packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts (1)
9-22: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winReplace unsafe CMS-shape assertions with type guards.
pagePropsand section entries originate asunknown; the assertions hide malformed CMS shapes rather than narrowing them. UseRecord<string, unknown>guards before readingsections,name,$componentKey, anddata.Also applies to: 36-36
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts` around lines 9 - 22, Update pushSections and the related recommendation-shelf checks to narrow unknown CMS values with Record<string, unknown> type guards before accessing sections, name, $componentKey, or data. Remove the unsafe CmsSection and pageProps shape assertions while preserving the existing valid-section filtering and recursion behavior.Sources: Coding guidelines, Path instructions
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/src/components/sections/RecommendationShelf/README.md`:
- Line 7: Update the RecommendationShelf README’s setup, runtime, and
troubleshooting guidance to document that merchants must add
StartRecommendationSession once under Global Sections to initialize sessions,
while enabling recommendations on each shelf only controls product fetching.
Remove or revise claims that the shelf toggle starts startRecommendationSession,
and ensure all repeated references—including the noted sections—consistently
describe the global-section requirement.
---
Outside diff comments:
In `@packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts`:
- Around line 84-114: Update the retry flow in the start-session logic so
hasRequestedStartRecommendationSession is reset to false when retry exhausts
without a defined result or the retry promise rejects. Keep the lock set after a
successful runStartRecommendationSessionRef.current call, ensuring later
attempts remain suppressed only when a session was actually started.
---
Nitpick comments:
In `@packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts`:
- Around line 9-22: Update pushSections and the related recommendation-shelf
checks to narrow unknown CMS values with Record<string, unknown> type guards
before accessing sections, name, $componentKey, or data. Remove the unsafe
CmsSection and pageProps shape assertions while preserving the existing
valid-section filtering and recursion behavior.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 846db0a3-c70e-4e31-bd4c-d5a596be9ef6
📒 Files selected for processing (12)
packages/core/cms/faststore/components/cms_component__recommendationshelf.jsoncpackages/core/cms/faststore/schema.jsonpackages/core/discovery.config.default.jspackages/core/src/Layout.tsxpackages/core/src/components/sections/RecommendationShelf/README.mdpackages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsxpackages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.tspackages/core/src/sdk/analytics/hooks/useStartRecommendationSession.tspackages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.tspackages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsxpackages/core/test/sdk/analytics/hasEnabledRecommendationShelf.test.tspackages/core/test/sdk/analytics/useStartRecommendationSession.test.ts
💤 Files with no reviewable changes (1)
- packages/core/discovery.config.default.js
…rate session start into RecommendationShelf Eliminate the StartRecommendationSession component, shifting its functionality to the RecommendationShelf. Introduce an `enableRecommendations` prop to control the personalization session initiation directly from the shelf, streamlining the setup process for merchants. Update related documentation and tests accordingly.
db98df8 to
6470480
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In `@packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts`:
- Around line 26-50: Add a test fixture or case that places an enabled
RecommendationShelf under globalSections and exercises
useStartRecommendationSession through that input path. Keep the existing
sections-based cases unchanged, and verify the enabled global shelf produces the
expected recommendation-session behavior.
- Around line 129-141: Update the test around useStartRecommendationSession to
capture the first renderHook result and call its unmount() before rendering the
second instance. Keep the existing assertions verifying
runStartRecommendationSession is called only once, so the test specifically
covers an unmount/remount lifecycle without a cookie.
- Around line 77-79: Replace the waitFor-wrapped negative assertions around
runStartRecommendationSession with direct not.toHaveBeenCalled assertions after
the intended hook effects have been flushed. Apply this to the affected cases so
delayed calls cannot satisfy the assertion during an intermediate poll.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yaml
Review profile: CHILL
Plan: Pro
Run ID: 03a2106d-7a87-4133-81fe-421e338cfbb9
📒 Files selected for processing (12)
packages/cli/src/utils/cp-schema.test.tspackages/core/cms/faststore/components/cms_component__recommendationshelf.jsoncpackages/core/cms/faststore/schema.jsonpackages/core/src/Layout.tsxpackages/core/src/components/sections/RecommendationShelf/README.mdpackages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsxpackages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.tspackages/core/src/sdk/analytics/hooks/useStartRecommendationSession.tspackages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.tspackages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsxpackages/core/test/sdk/analytics/hasEnabledRecommendationShelf.test.tspackages/core/test/sdk/analytics/useStartRecommendationSession.test.ts
💤 Files with no reviewable changes (1)
- packages/cli/src/utils/cp-schema.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- packages/core/cms/faststore/components/cms_component__recommendationshelf.jsonc
- packages/core/src/Layout.tsx
- packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts
- packages/core/test/sdk/analytics/hasEnabledRecommendationShelf.test.ts
- packages/core/cms/faststore/schema.json
- packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx
- packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts
- packages/core/src/components/sections/RecommendationShelf/README.md
- packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.ts
- packages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx
| const enabledPageProps = { | ||
| sections: [ | ||
| { | ||
| name: 'RecommendationShelf', | ||
| data: { enableRecommendations: true }, | ||
| }, | ||
| ], | ||
| } | ||
|
|
||
| const multipleEnabledShelvesPageProps = { | ||
| sections: [ | ||
| { | ||
| name: 'RecommendationShelf', | ||
| data: { enableRecommendations: true, campaignVrn: 'vrn:a' }, | ||
| }, | ||
| { | ||
| name: 'RecommendationShelf', | ||
| data: { enableRecommendations: true, campaignVrn: 'vrn:b' }, | ||
| }, | ||
| { | ||
| name: 'ProductShelf', | ||
| data: {}, | ||
| }, | ||
| ], | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
Cover the globalSections input path.
hasEnabledRecommendationShelf also scans globalSections, but every enabled fixture here uses only sections. Add a case with an enabled shelf under globalSections; otherwise a regression in the CMS Global Section flow could pass unnoticed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts`
around lines 26 - 50, Add a test fixture or case that places an enabled
RecommendationShelf under globalSections and exercises
useStartRecommendationSession through that input path. Keep the existing
sections-based cases unchanged, and verify the enabled global shelf produces the
expected recommendation-session behavior.
| await waitFor(() => { | ||
| expect(runStartRecommendationSession).not.toHaveBeenCalled() | ||
| }) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== file excerpt =="
sed -n '1,140p' packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts | cat -n
echo "== package files related =="
fd -i 'useStartRecommendationSession|recommendation' packages/core -t f | sed -n '1,80p'
echo "== imports and usage in test =="
rg -n "waitFor|react-dom/client|timer|setTimeout|advanceTimers|fakeTimers|runStartRecommendationSession|useStartRecommendationSession" packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts packages -g '!**/node_modules/**' | sed -n '1,220p'Repository: vtex/faststore
Length of output: 25644
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== hook implementation =="
sed -n '1,170p' packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts | cat -n
echo "== package.json vitest/react-testing versions =="
for f in package.json pnpm-lock.yaml; do
if [ -f "$f" ]; then
echo "--- $f ---"
rg -n "`@testing-library/react`|vitest|`@vitest/`|resolve" "$f" | sed -n '1,120p'
fi
done
echo "== deterministic waitFor behavior probe =="
node - <<'JS'
let fnCalls = 0
const passedAssertions = []
const assertion = () => {
fnCalls++
passedAssertions.push({ callsAtFirstCall: fnCalls })
return false
}
for (let i = 0; i < 3; i++) {
fnCalls = 0
const cb = () => {
try {
if (assertion()) return
} catch {
return true
}
return true
}
cb()
}
console.log(JSON.stringify(passedAssertions))
JSRepository: vtex/faststore
Length of output: 5380
🌐 Web query:
@testing-library/react waitFor function throws on negative assertions first poll not toHaveBeenCalled
💡 Result:
Using waitFor to assert that a condition does not happen—such as expect(mock).not.toHaveBeenCalled()—will cause the test to pass immediately [1]. This is because waitFor retries until the callback does not throw an error [2]; since the condition is true at the start of the test, the assertion passes on the first attempt, and waitFor resolves successfully without actually waiting for future state changes [1][3]. To correctly assert that something does not happen, you must use an inverse assertion or ensure the environment is settled first [4][3]. Recommended approaches: 1. Use an inverse assertion (The "Promise" approach): Instead of waiting for the absence, wait for the presence of the event to occur and assert that this operation eventually fails [4]. // Example: Asserting a notification never appears const notificationPromise = waitFor( => { expect(screen.getByText('Success!')).toBeInTheDocument; }); // We expect this promise to reject because the notification should NOT appear await expect(notificationPromise).rejects.toThrow; 2. Settle the UI first: If you are waiting for an effect (like a mock call) that should not happen after a specific user action, first wait for a visible change that indicates the UI has finished processing, then assert the absence synchronously [5][3]. // 1. Trigger action fireEvent.click(button); // 2. Wait for a visible "anchor" to ensure the system is settled await screen.findByText('Task Complete'); // 3. Synchronously assert the absence expect(mockFunction).not.toHaveBeenCalled; Avoid using waitFor for negative assertions; it will not behave as a "wait for this to never happen" utility and often leads to false positives [5][1][3].
Citations:
- 1: https://stackoverflow.com/questions/73826316/how-can-a-jest-test-waitfor-a-mocked-function-not-to-have-been-called
- 2: https://testing-library.com/docs/dom-testing-library/api-async/
- 3: https://qaskills.sh/blog/react-testing-library-common-mistakes-2026
- 4: https://www.epicweb.dev/inverse-assertions
- 5: New Rule Proposal: no-unsettled-absence-query testing-library/eslint-plugin-testing-library#1237
Avoid waitFor for negative assertions that can pass immediately.
waitFor(() => expect(...).not.toHaveBeenCalled()) resolves on the first poll after the hook effect runs, so a delayed call still passes in cases 1, 2, and 3. Remove the waitFor and assert the mock was not called after the intended effects are flushed.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts`
around lines 77 - 79, Replace the waitFor-wrapped negative assertions around
runStartRecommendationSession with direct not.toHaveBeenCalled assertions after
the intended hook effects have been flushed. Apply this to the affected cases so
delayed calls cannot satisfy the assertion during an intermediate poll.
| it('does not start a second session when the hook mounts again without a cookie', async () => { | ||
| getCookie.mockReturnValue(undefined) | ||
|
|
||
| renderHook(() => useStartRecommendationSession(enabledPageProps)) | ||
|
|
||
| await waitFor(() => { | ||
| expect(runStartRecommendationSession).toHaveBeenCalledTimes(1) | ||
| }) | ||
|
|
||
| renderHook(() => useStartRecommendationSession(enabledPageProps)) | ||
|
|
||
| await waitFor(() => { | ||
| expect(runStartRecommendationSession).toHaveBeenCalledTimes(1) |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts'
if [ ! -f "$file" ]; then
echo "missing $file"
fd -a 'useStartRecommendationSession.test.ts' .
exit 0
fi
echo "== file outline =="
ast-grep outline "$file" --view compact || true
echo "== relevant lines =="
cat -n "$file" | sed -n '1,220p'
echo "== hook/source references =="
rg -n "useStartRecommendationSession|runStartRecommendationSession|useEffect|Unmount" packages/core -g '*.ts' -g '*.tsx' | head -n 200Repository: vtex/faststore
Length of output: 20094
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file='packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts'
echo "== hook source =="
cat -n "$file" | sed -n '1,180p'
echo "== package test deps =="
cat package.json | jq '.devDependencies["`@testing-library/react`"], .devDependencies.vitest, .dependencies.react' 2>/dev/null || true
if [ -f packages/core/package.json ]; then
cat packages/core/package.json | jq '.devDependencies["`@testing-library/react`"], .devDependencies.vitest, .dependencies.react' 2>/dev/null || true
fi
echo "== lockfile vite test availability =="
rg -n '"`@testing-library/react`|"vite-node|"`@testing-library/react-hooks`' pnpm-lock.yaml package.json packages/core/package.json -g 'pnpm-lock.yaml' -g 'package.json' | head -n 60 || true
echo "== behavioral probe of renderHook lifecycle from source text =="
python3 - <<'PY'
from pathlib import Path
p=Path('packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts')
s=p.read_text()
checks = {
'imports useRef': 'useRef' in s,
'imports useEffect': 'useEffect' in s,
'has lock flag': 'startRecommendationSessionLock' in s or 'startRecommendation' in s,
'uses useRef current': '.current' in s,
'has cleanup/return': 'return' in s and s.find('useEffect') != -1,
'effect has no dependencies array': s.find('useEffect(()') != -1 and s.find('useEffect(()', s.find('useEffect(()'), s.find('useEffect(()') + 1000) != -1,
}
for k,v in checks.items():
print(f'{k}: {v}')
PYRepository: vtex/faststore
Length of output: 6077
Unmount before testing a remount.
The second renderHook adds a second mounted instance rather than replacing the first. Capture the first result and call unmount() before rendering again so this tests the lifecycle case the test name describes.
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
In `@packages/core/test/sdk/analytics/useStartRecommendationSession.test.ts`
around lines 129 - 141, Update the test around useStartRecommendationSession to
capture the first renderHook result and call its unmount() before rendering the
second instance. Keep the existing assertions verifying
runStartRecommendationSession is called only once, so the test specifically
covers an unmount/remount lifecycle without a cookie.
|
| errorMessage: 'Failed to upload CMS schema', | ||
| interactive: true, | ||
| }) | ||
| expect(runCommandSyncMock.mock.calls[0][0].cmd).not.toContain('-l') |
There was a problem hiding this comment.
do we need to remove this?
| }) | ||
| }) | ||
|
|
||
| it('starts a session only once when the page has multiple enabled RecommendationShelves', async () => { |

0 New Issues
0 Fixed Issues
0 Accepted Issues
Summary
experimental.enableRecommendationsflag andLayoutwiring with a CMS Start Recommendation Session Global Section, so merchants can opt into Recommendations without changing store code.RecommendationShelffetching when placed via CMS; session start is now controlled by addingStartRecommendationSessiononce under Global Sections.schema.json/sections.json) and document the new setup in the RecommendationShelf README.Test plan
pnpm vitest run test/sdk/analytics/useStartRecommendationSession.test.ts test/components/StartRecommendationSession/StartRecommendationSession.test.tsx test/components/RecommendationShelf/RecommendationShelf.browser.test.tsxinpackages/coreexperimental.enableRecommendationsis no longer present indiscovery.config.default.jsSummary by CodeRabbit
New Features
Behavior Changes
Documentation
Tests