feat: email query param override for chat#1647
Conversation
Read email query param from URL on chat/landing pages and thread it through the component tree to include in the /api/chat request body. Co-Authored-By: Paperclip <noreply@paperclip.ing>
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
Warning Rate limit exceeded
Your organization is not enrolled in usage-based pricing. Contact your admin to enable usage-based pricing to continue reviews beyond the rate limit, or try again in 10 minutes and 38 seconds. ⌛ How to resolve this issue?After the wait time has elapsed, a review can be triggered using the We recommend that you space out your commits to avoid hitting the rate limit. 🚦 How do rate limits work?CodeRabbit enforces hourly rate limits for each developer per organization. Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout. Please see our FAQ for further information. ℹ️ Review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yaml Review profile: CHILL Plan: Pro Run ID: 📒 Files selected for processing (7)
📝 WalkthroughWalkthroughEmail parameter support is added across the chat application's entire stack. The Changes
Estimated code review effort🎯 2 (Simple) | ⏱️ ~12 minutes Suggested reviewers
Poem
🚥 Pre-merge checks | ❌ 1❌ Failed checks (1 warning)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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 |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
app/page.tsx (1)
11-18: Consider extracting shared param parsing logic.Both
app/page.tsxandapp/chat/page.tsxhave nearly identical param extraction logic. For DRY compliance and consistent behavior, consider extracting a utility function.♻️ Optional: Shared utility extraction
// lib/parseSearchParams.ts export function parseSearchParams(params: Record<string, string | string[] | undefined> | undefined) { const getString = (key: string) => { const value = params?.[key]; return Array.isArray(value) ? value[0] : value; }; return { initialMessage: getString('q'), email: getString('email'), }; }Then in both pages:
const params = await searchParams; const { initialMessage, email } = parseSearchParams(params);🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@app/page.tsx` around lines 11 - 18, The param parsing in Home (function Home in app/page.tsx) duplicates logic used in app/chat/page.tsx; extract this into a shared utility (e.g., parseSearchParams) that accepts the searchParams object and returns { initialMessage, email } using a helper to normalize string|string[] values, then update Home to call parseSearchParams(await searchParams) and pass the returned initialMessage into getMessages and email into HomePage; ensure generateUUID() and getMessages(...) usage remains unchanged and only the params extraction is moved to the new utility.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@app/chat/page.tsx`:
- Around line 13-16: The code currently asserts searchParams values as strings
which breaks if params are arrays; normalize values first by checking
Array.isArray on params?.q and params?.email and extracting the first element
(or undefined) before calling getMessages or using email, e.g., compute a
safeInitialMessage and safeEmail from params and pass safeInitialMessage to
getMessages so downstream code only ever receives string | undefined rather than
string | string[].
In `@app/page.tsx`:
- Around line 13-16: The code assumes searchParams keys are strings but may be
arrays; update how params is read so initialMessage and email handle array
values safely: when retrieving params (the const params, usage of initialMessage
and email) coerce params?.q and params?.email to strings by checking if they are
arrays (e.g., Array.isArray) and picking the first element or joining as needed,
then pass that sanitized string into getMessages(initialMessage) and any
downstream logic; ensure getMessages is called only with a string and email is
typed as string | undefined after normalization.
---
Nitpick comments:
In `@app/page.tsx`:
- Around line 11-18: The param parsing in Home (function Home in app/page.tsx)
duplicates logic used in app/chat/page.tsx; extract this into a shared utility
(e.g., parseSearchParams) that accepts the searchParams object and returns {
initialMessage, email } using a helper to normalize string|string[] values, then
update Home to call parseSearchParams(await searchParams) and pass the returned
initialMessage into getMessages and email into HomePage; ensure generateUUID()
and getMessages(...) usage remains unchanged and only the params extraction is
moved to the new utility.
🪄 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: 5dae6817-3948-4c52-b911-349cf7950e44
📒 Files selected for processing (6)
app/chat/page.tsxapp/page.tsxcomponents/Home/HomePage.tsxcomponents/VercelChat/chat.tsxhooks/useVercelChat.tsproviders/VercelChatProvider.tsx
There was a problem hiding this comment.
No issues found across 6 files
Confidence score: 5/5
- Automated review surfaced no issues in the provided summaries.
- No files require special attention.
Requires human review: Modifies the core chat API request body to include an email override for user impersonation/context, which has security and authorization implications requiring human review.
Use Array.isArray checks instead of type assertions for q and email search params to handle duplicate query param edge case. Co-Authored-By: Paperclip <noreply@paperclip.ing>
There was a problem hiding this comment.
0 issues found across 2 files (changes from recent commits).
Requires human review: This PR introduces a user context override via query parameters (email), which is a security-sensitive change that modifies API request bodies and requires human verification of authorization logic.
…/{email}
Instead of passing email to /api/chat, the Chat component resolves
email → accountId using the new accounts endpoint, then passes
accountId in the chat body using the existing override mechanism.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
3 issues found across 4 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="hooks/useVercelChat.ts">
<violation number="1" location="hooks/useVercelChat.ts:174">
P2: `accountIdOverride` in the request body will be ignored for authenticated users because the server always overwrites `accountId` with the header-derived value. The override feature won’t take effect unless the backend accepts an explicit override field or conditional logic.</violation>
</file>
<file name="hooks/useEmailAccountId.ts">
<violation number="1" location="hooks/useEmailAccountId.ts:18">
P2: Reset the accountId when `email` is missing or changes; otherwise the hook can return a stale accountId from a prior email.</violation>
<violation number="2" location="hooks/useEmailAccountId.ts:36">
P2: Effect lacks cancellation or latest-email check, so slower responses can overwrite accountId with stale data after email changes.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.
There was a problem hiding this comment.
DRY - does this match how we accept the api override query param? We should keep page query param override management consistent.
components/VercelChat/chat.tsx
Outdated
| id: string; | ||
| reportId?: string; | ||
| initialMessages?: UIMessage[]; | ||
| email?: string; |
There was a problem hiding this comment.
How can we eliminate prop drilling of the email param?
hooks/useEmailAccountId.ts
Outdated
| }, [email, getAccessToken]); | ||
|
|
||
| return accountId; | ||
| } |
There was a problem hiding this comment.
DRY - is this following the same architecture as the api query param?
Follow the ApiOverrideSync pattern: AccountOverrideSync reads ?email=
query param, resolves it to an accountId via GET /api/accounts/{email},
and stores it in session storage. useVercelChat reads the override from
session storage. No prop drilling through 6 files.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
providers/AccountOverrideSync.tsx
Outdated
| const searchParams = useSearchParams(); | ||
| const { getAccessToken } = usePrivy(); | ||
|
|
||
| useEffect(() => { |
There was a problem hiding this comment.
Would this be more efficient using tanstack useQuery?
providers/Providers.tsx
Outdated
| > | ||
| <WagmiProvider> | ||
| <PrivyProvider> | ||
| <AccountOverrideSync /> |
There was a problem hiding this comment.
Why is this provider at a different level than ApiOverrideSync?
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Replaces manual useEffect fetch with useQuery for caching and deduplication. Added comment explaining why placement differs from ApiOverrideSync (needs usePrivy for auth). Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
providers/AccountOverrideSync.tsx
Outdated
|
|
||
| const { data: accountId } = useQuery({ | ||
| queryKey: ["accountOverride", emailParam], | ||
| queryFn: async () => { |
There was a problem hiding this comment.
Can this query fn be moved to a lib file to follow SRP?
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
1 issue found across 2 files (changes from recent commits).
Prompt for AI agents (unresolved issues)
Check if these issues are valid — if so, understand the root cause of each and fix them. If appropriate, use sub-agents to investigate and fix each issue separately.
<file name="lib/accounts/fetchAccountIdByEmail.ts">
<violation number="1" location="lib/accounts/fetchAccountIdByEmail.ts:20">
P1: Only treat 404 as “not found”; other HTTP errors should be surfaced instead of being silently converted to null.</violation>
</file>
Reply with feedback, questions, or to request a fix. Tag @cubic-dev-ai to re-run a review, or fix all with cubic.
Shows a fixed pill at the top center with "Viewing as {email}" and an X
button to clear the override when ?email= is active.
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
components/AccountOverrideBadge.tsx
Outdated
| const searchParams = useSearchParams(); | ||
| const router = useRouter(); | ||
| const [isActive, setIsActive] = useState(false); | ||
| const email = searchParams.get("email"); | ||
|
|
||
| useEffect(() => { | ||
| if (!email || email === "clear") { | ||
| setIsActive(false); | ||
| return; | ||
| } | ||
|
|
||
| const accountId = window.sessionStorage.getItem( | ||
| ACCOUNT_OVERRIDE_STORAGE_KEY, | ||
| ); | ||
| setIsActive(!!accountId); | ||
| }, [email]); |
There was a problem hiding this comment.
dry - why isn't this using the existing provider?
Reads from the same queryKey as AccountOverrideSync instead of duplicating session storage checks. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
components/AccountOverrideBadge.tsx
Outdated
| const { data: accountId } = useQuery({ | ||
| queryKey: ["accountOverride", email], | ||
| queryFn: async () => { | ||
| const accessToken = await getAccessToken(); | ||
| if (!accessToken) return null; | ||
| return fetchAccountIdByEmail(email!, accessToken); | ||
| }, | ||
| enabled: !!email && email !== "clear", | ||
| staleTime: Infinity, | ||
| }); |
There was a problem hiding this comment.
DRY - why do we need this useQuery instead of using the existing provider?
Badge polls session storage instead of duplicating the useQuery. AccountOverrideSync writes it, badge reads it. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
You're iterating quickly on this pull request. To help protect your rate limits, cubic has paused automatic reviews on new pushes for now—when you're ready for another review, comment |
No polling or state needed — if ?email= is in the URL, show the badge. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Browser Testing Results (Preview Deployment)Preview URL: ?email=jessica@rostrumrecords.com
Without ?email=
|
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Single source of truth for override state. Badge and useVercelChat both consume useAccountOverride() context. Override persists across page refreshes via session storage. Badge shows even after navigation. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
|
|
||
| export function useAccountOverride() { | ||
| return useContext(AccountOverrideContext); | ||
| } |
There was a problem hiding this comment.
SRP - create lib files so the provider has less than 100 lines of code.
Only treat 404 as "not found". Other HTTP errors (401, 500, etc.) should surface so useQuery can retry or show error state. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Moved session storage read/write/clear to lib/accounts/accountOverrideStorage.ts. Provider is now 86 lines. Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
SRP
- move any functions with names different from the file name do a different lib file with the same file name as the function name.
| useEffect(() => { | ||
| if (emailParam === "clear") { | ||
| clearStoredAccountOverride(); | ||
| setStored({ accountId: null, email: null }); | ||
| return; | ||
| } | ||
| if (resolvedAccountId && email) { | ||
| setStoredAccountOverride(resolvedAccountId, email); | ||
| setStored({ accountId: resolvedAccountId, email }); | ||
| } | ||
| }, [emailParam, email, resolvedAccountId]); | ||
|
|
||
| const clear = useCallback(() => { | ||
| clearStoredAccountOverride(); | ||
| setStored({ accountId: null, email: null }); | ||
| const params = new URLSearchParams(searchParams.toString()); | ||
| params.delete("email"); | ||
| const newPath = params.toString() | ||
| ? `${window.location.pathname}?${params.toString()}` | ||
| : window.location.pathname; | ||
| router.replace(newPath); | ||
| }, [searchParams, router]); |
There was a problem hiding this comment.
Can either of these be made more efficient with the use of the tanstack package? useQuery or useMutation?
- Split accountOverrideStorage.ts into 3 files matching function names - Moved storage sync into useQuery queryFn, removed useEffect Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
There was a problem hiding this comment.
Should these 3 libs be moved to
- actual: lib/accounts/clearStoredAccountOverride.ts
- suggested: lib/accounts/override/clearStoredAccountOverride.ts
Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
Summary
emailquery param from the chat/landing page URLsemailin the/api/chatrequest body when present?email=customer@example.comTest plan
?email=customer@example.compasses the email in the API request body🤖 Generated with Claude Code
Summary by cubic
Adds an optional
emailquery param to preview customer chats (REC-52). Resolves it to anaccountIdon the client, stores a session override, injects it into/api/chat, and shows a top “Viewing as {email}” badge with one‑click clear.Refactors
AccountOverrideSyncwithAccountOverrideProviderthat reads?email=, resolves viaGET /api/accounts/{email}using@tanstack/react-query+@privy-io/react-auth, and persists tosessionStorageunderACCOUNT_OVERRIDE_STORAGE_KEY(supports?email=clear).useVercelChatnow consumesuseAccountOverride()to includeaccountIdin the chat body. AddedAccountOverrideBadgeinapp/layout.tsx. ExtractedfetchAccountIdByEmailtolib/accounts/.getStoredAccountOverride,setStoredAccountOverride, andclearStoredAccountOverride; moved them tolib/accounts/override/. Storage sync now happens in theuseQueryqueryFn(nouseEffect).Bug Fixes
qandemailsearch params by using the first value.amber-400in dark mode.fetchAccountIdByEmail: throw on non-404 HTTP errors so@tanstack/react-querycan retry or surface errors.Written for commit cfb889e. Summary will update on new commits.
Summary by CodeRabbit
Release Notes