Skip to content

feat(core): move recommendation session start to CMS Global Section - #3414

Merged
eduardoformiga merged 2 commits into
devfrom
feat/start-recommendation-session-cms
Jul 22, 2026
Merged

eduardoformiga merged 2 commits into
devfrom
feat/start-recommendation-session-cms

Conversation

@thiagopereira-vtex

@thiagopereira-vtex thiagopereira-vtex commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Summary

  • Replace the experimental.enableRecommendations flag and Layout wiring with a CMS Start Recommendation Session Global Section, so merchants can opt into Recommendations without changing store code.
  • Keep RecommendationShelf fetching when placed via CMS; session start is now controlled by adding StartRecommendationSession once under Global Sections.
  • Regenerate CMS schemas (schema.json / sections.json) and document the new setup in the RecommendationShelf README.

Test plan

  • Add Start Recommendation Session once under Global Sections in CMS
  • Add Recommendation Shelf to a page with a valid campaign VRN and confirm products render
  • Remove Start Recommendation Session from Global Sections and confirm the shelf no longer starts a personalization session
  • Run pnpm vitest run test/sdk/analytics/useStartRecommendationSession.test.ts test/components/StartRecommendationSession/StartRecommendationSession.test.tsx test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx in packages/core
  • Confirm experimental.enableRecommendations is no longer present in discovery.config.default.js

Summary by CodeRabbit

  • New Features

    • Added an Enable recommendations? toggle to the Recommendation Shelf CMS component.
    • When enabled, shelves can start a personalization session once per browser session and render personalized products; recommendations stay off by default.
  • Behavior Changes

    • Recommendations opt-in is now determined per page by enabled shelves (instead of a global experimental flag), and session start is prevented from triggering multiple times before the cookie is set.
  • Documentation

    • Added a Recommendation Shelf documentation page covering configuration, supported campaigns, and runtime/troubleshooting behavior.
  • Tests

    • Updated Recommendation Shelf and session-start test coverage to match the new opt-in behavior.

@thiagopereira-vtex
thiagopereira-vtex requested a review from a team as a code owner July 15, 2026 19:14
@thiagopereira-vtex
thiagopereira-vtex requested review from lariciamota and ommeirelles and removed request for a team July 15, 2026 19:14
@coderabbitai

coderabbitai Bot commented Jul 15, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Walkthrough

RecommendationShelf 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.

Changes

Recommendation opt-in flow

Layer / File(s) Summary
CMS opt-in and shelf gating
packages/core/cms/faststore/..., packages/core/src/components/sections/RecommendationShelf/*, packages/core/discovery.config.default.js
Adds enableRecommendations, defaults it to false, removes the global configuration flag, and gates shelf recommendation fetching through the component prop.
Page-level session startup
packages/core/src/Layout.tsx, packages/core/src/sdk/analytics/...
Detects enabled shelves in page props, starts the session only when needed, and prevents duplicate starts across rerenders or remounts.
Behavior validation and documentation
packages/core/test/..., packages/core/src/components/sections/RecommendationShelf/README.md, packages/cli/src/utils/cp-schema.test.ts
Updates component and hook tests, adds coverage for page-prop detection, and documents configuration, runtime behavior, campaign types, customization, caching, and troubleshooting.

Estimated code review effort: 3 (Moderate) | ~25 minutes

Possibly related PRs

  • vtex/faststore#3403: Implements the related RecommendationShelf personalization session flow and gating.
  • vtex/faststore#3413: Updates the RecommendationShelf documentation and opt-in behavior.

Suggested labels: enhancement

Suggested reviewers: lariciamota, ommeirelles, eduardoformiga

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 75.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly reflects the main change: moving recommendation session start into CMS-driven setup instead of a global experimental flag.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/start-recommendation-session-cms

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.json

Traceback (most recent call last):
File "/usr/local/bin/checkov", line 2, in
from checkov.main import Checkov
ModuleNotFoundError: No module named 'checkov'


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.

@codesandbox-ci

codesandbox-ci Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

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.

@pkg-pr-new

pkg-pr-new Bot commented Jul 15, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@faststore/api

npm i https://pkg.pr.new/vtex/faststore/@faststore/api@6470480

@faststore/cli

npm i https://pkg.pr.new/vtex/faststore/@faststore/cli@6470480

@faststore/components

npm i https://pkg.pr.new/vtex/faststore/@faststore/components@6470480

@faststore/core

npm i https://pkg.pr.new/vtex/faststore/@faststore/core@6470480

@faststore/diagnostics

npm i https://pkg.pr.new/vtex/faststore/@faststore/diagnostics@6470480

@faststore/lighthouse

npm i https://pkg.pr.new/vtex/faststore/@faststore/lighthouse@6470480

@faststore/sdk

npm i https://pkg.pr.new/vtex/faststore/@faststore/sdk@6470480

@faststore/ui

npm i https://pkg.pr.new/vtex/faststore/@faststore/ui@6470480

commit: 6470480

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.
@thiagopereira-vtex
thiagopereira-vtex force-pushed the feat/start-recommendation-session-cms branch from a69db55 to 8589056 Compare July 15, 2026 19:40

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 renatomaurovtex left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.json are consistent with the new .jsonc source (identical StartRecommendationSession block) — these are the checked-in CMS artifacts uploaded via vtex content upload-schema, not a __generated__ violation.
  • Flag removal is complete: a repo-wide search for enableRecommendations on dev returns 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 StartRecommendationSession component test added. ✅
  • feat(core): title + scope valid; dynamic import with { ssr: false } mirrors RecommendationShelf registration. ✅

💬 [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.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 win

Release the lock when all session-start retries fail.

If every attempt returns undefined or the retry rejects, hasRequestedStartRecommendationSession stays true without 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 win

Replace unsafe CMS-shape assertions with type guards.

pageProps and section entries originate as unknown; the assertions hide malformed CMS shapes rather than narrowing them. Use Record<string, unknown> guards before reading sections, name, $componentKey, and data.

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

📥 Commits

Reviewing files that changed from the base of the PR and between a69db55 and db98df8.

📒 Files selected for processing (12)
  • packages/core/cms/faststore/components/cms_component__recommendationshelf.jsonc
  • packages/core/cms/faststore/schema.json
  • packages/core/discovery.config.default.js
  • packages/core/src/Layout.tsx
  • packages/core/src/components/sections/RecommendationShelf/README.md
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.ts
  • packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts
  • packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts
  • packages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx
  • packages/core/test/sdk/analytics/hasEnabledRecommendationShelf.test.ts
  • packages/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.
@thiagopereira-vtex
thiagopereira-vtex force-pushed the feat/start-recommendation-session-cms branch from db98df8 to 6470480 Compare July 22, 2026 20:26

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

📥 Commits

Reviewing files that changed from the base of the PR and between db98df8 and 6470480.

📒 Files selected for processing (12)
  • packages/cli/src/utils/cp-schema.test.ts
  • packages/core/cms/faststore/components/cms_component__recommendationshelf.jsonc
  • packages/core/cms/faststore/schema.json
  • packages/core/src/Layout.tsx
  • packages/core/src/components/sections/RecommendationShelf/README.md
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.tsx
  • packages/core/src/components/sections/RecommendationShelf/RecommendationShelf.types.ts
  • packages/core/src/sdk/analytics/hooks/useStartRecommendationSession.ts
  • packages/core/src/sdk/analytics/utils/hasEnabledRecommendationShelf.ts
  • packages/core/test/components/RecommendationShelf/RecommendationShelf.browser.test.tsx
  • packages/core/test/sdk/analytics/hasEnabledRecommendationShelf.test.ts
  • packages/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

Comment on lines +26 to +50
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: {},
},
],
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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.

Comment on lines +77 to +79
await waitFor(() => {
expect(runStartRecommendationSession).not.toHaveBeenCalled()
})

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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))
JS

Repository: 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:


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.

Comment on lines +129 to +141
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🎯 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 200

Repository: 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}')
PY

Repository: 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.

@sonar-workflows

Copy link
Copy Markdown

errorMessage: 'Failed to upload CMS schema',
interactive: true,
})
expect(runCommandSyncMock.mock.calls[0][0].cmd).not.toContain('-l')

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

do we need to remove this?

})
})

it('starts a session only once when the page has multiple enabled RecommendationShelves', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nice!

@eduardoformiga
eduardoformiga merged commit b2fd350 into dev Jul 22, 2026
11 checks passed
@eduardoformiga
eduardoformiga deleted the feat/start-recommendation-session-cms branch July 22, 2026 21:39
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.

4 participants