Skip to content

fix: Add validation for required body in CustomizePostDialog#46

Open
amaldinesh7 wants to merge 4 commits into
mainfrom
fix/body-required-validation
Open

fix: Add validation for required body in CustomizePostDialog#46
amaldinesh7 wants to merge 4 commits into
mainfrom
fix/body-required-validation

Conversation

@amaldinesh7
Copy link
Copy Markdown
Owner

@amaldinesh7 amaldinesh7 commented Mar 3, 2026

Summary

Adds inline validation in the CustomizePostDialog when a subreddit requires a description but the effective body content is empty. This provides immediate user feedback in the customize dialog rather than waiting for preflight validation to catch the issue.

Key Changes

  • Body validation logic -- checks if body is required (body_restriction_policy === 'required') and displays an error message when the effective body is empty
  • Save button disabled state -- prevents saving when validation fails, ensuring users address the issue before proceeding
  • Error display in both states -- shows validation error whether using custom body or falling back to global body

Made with Cursor

Summary by CodeRabbit

  • New Features
    • Adds analytics tracking to the app.
    • Checkout success now shows a confirming/loading phase and automatically verifies payment before showing the final Pro success UI.
    • Auth data refreshes more frequently and when the tab regains focus.
  • Bug Fixes
    • Shows an inline error under the post body input and disables Save when local body validation fails; layout and counter aligned.
  • Tests
    • Adds full end-to-end demo test; updates flows to wait for dialogs and dynamic post results, introduces streaming queue mock and updates authenticated mock to include paid entitlement and expanded limits.
  • Chores
    • Removed runtime enforcement that treated a subreddit’s "body required" policy as a blocking error.

Show error message and disable Save button when a subreddit requires a
description but the effective body is empty. This provides immediate
feedback in the customize dialog rather than waiting for preflight
validation.

Made-with: Cursor
@vercel
Copy link
Copy Markdown
Contributor

vercel Bot commented Mar 3, 2026

The latest updates on your projects. Learn more about Vercel for GitHub.

Project Deployment Actions Updated (UTC)
reddit-multi-poster Ready Ready Preview, Comment Mar 3, 2026 8:50am

@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented Mar 3, 2026

📝 Walkthrough

Walkthrough

Adds client-side body-required validation UI and disables Save when missing; removes runtime enforcement of subreddit body-required in preflight; tightens auth SWR revalidation; integrates Vercel Analytics; replaces checkout success with a polling-based payment confirmation flow; adds streaming mock updates and new end-to-end tests.

Changes

Cohort / File(s) Summary
Post customization UI
components/subreddit-picker/CustomizePostDialog.tsx
Adds bodyError derived from bodyRequired and body content; renders inline error beneath body input; adjusts layout for counter/error; disables Save when error present.
Preflight validation
lib/preflightValidation.ts
Removes runtime enforcement that pushed a BODY_REQUIRED ValidationIssue for subreddits with body_restriction_policy === 'required'; keeps subsequent body validations when body exists.
Auth & app lifecycle
contexts/AuthContext.tsx, pages/_app.tsx, package.json
Enables revalidateOnFocus, reduces SWR dedupe interval to 60s; adds @vercel/analytics dependency and mounts <Analytics /> in _app.
Checkout / payment confirmation
pages/checkout/success.tsx
Introduces usePaymentConfirmation hook that polls /api/me until entitlement === 'paid' (with timeout); mutates SWR on success; shows confirming/loading UI then final Pro UI and navigates back to app.
E2E tests & mocks
tests/demo/full-product-demo.spec.ts, tests/flows/*, tests/flows/helpers.ts, tests/mocks/handlers.ts
Adds full-product demo test; updates flow tests to wait for dialog and dynamic post button text; changes subreddit toggle interaction to be state-aware; adds streaming response builder for /api/queue/process; augments authenticated mock with entitlement: 'paid' and expanded limits.

Sequence Diagram(s)

sequenceDiagram
  participant User
  participant Browser
  participant App as Next.js App
  participant API as /api/me
  participant SWR as SWR Cache
  participant Router

  User->>Browser: Land on /checkout/success
  Browser->>App: Render success page (usePaymentConfirmation)
  App->>API: Poll /api/me every POLL_INTERVAL_MS
  API-->>App: Respond with auth (entitlement)
  alt entitlement === 'paid'
    App->>SWR: mutate('/api/me') to refresh auth
    App->>Router: navigate back to app
    App-->>User: Show "You're Pro now!" UI
  else still pending / timeout
    App-->>User: Show "Confirming your upgrade…" loading UI
    loop until timeout or paid
      App->>API: poll again
    end
  end
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Possibly related PRs

Poem

A rabbit taps keys with a tiny drum, 🐇
"Save won't hop if the body is numb."
Polls hum in the night until Pro is shown,
Analytics listens, auth wakes up grown,
Hooray — posts and payments find their home. ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: adding validation for required body in CustomizePostDialog, which is the primary functional change across multiple related files.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch fix/body-required-validation

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 and usage tips.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (2)
components/subreddit-picker/CustomizePostDialog.tsx (2)

282-284: Apply same accessibility attributes here.

For consistency and accessibility, apply the same role="alert" attribute to this error message as well.

♿ Proposed fix
                {bodyError && (
-                  <p className="text-xs text-red-500 mt-1">{bodyError}</p>
+                  <p id="body-error-global" role="alert" className="text-xs text-red-500 mt-1">{bodyError}</p>
                )}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@components/subreddit-picker/CustomizePostDialog.tsx` around lines 282 - 284,
The body error message in CustomizePostDialog (the conditional render using
bodyError) is missing accessibility attributes; update the <p> element that
displays bodyError to include role="alert" (matching the other error messages)
so screen readers announce it immediately; locate the conditional rendering that
references the bodyError variable in the CustomizePostDialog component and add
role="alert" to that paragraph element.

262-267: Add accessibility attributes for the error message.

The error message is not accessible to screen readers. Add role="alert" or aria-live="polite" to announce the error, and associate it with the textarea using aria-describedby.

♿ Proposed accessibility fix
                <div className="flex justify-between items-center mt-1">
                  {bodyError ? (
-                    <p className="text-xs text-red-500">{bodyError}</p>
+                    <p id="body-error" role="alert" className="text-xs text-red-500">{bodyError}</p>
                  ) : (
                    <span />
                  )}

Then add aria-describedby="body-error" and aria-invalid={!!bodyError} to the Textarea at line 243:

<Textarea
  ref={bodyRef}
  value={customBody}
  onChange={(e) => setCustomBody(e.target.value.slice(0, bodyMaxLength))}
  placeholder="Custom description for this community"
  className="resize-none min-h-[80px] overflow-hidden pr-14"
  rows={3}
  aria-describedby={bodyError ? "body-error" : undefined}
  aria-invalid={!!bodyError}
/>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@components/subreddit-picker/CustomizePostDialog.tsx` around lines 262 - 267,
The error paragraph for bodyError is not announced to screen readers and not
linked to the textarea; update the error element rendered in CustomizePostDialog
to include an id (e.g., "body-error") and an accessibility attribute such as
role="alert" or aria-live="polite" (use the existing conditional that renders
{bodyError} to add these). Then update the Textarea component (the one using
bodyRef/customBody) to include aria-describedby={bodyError ? "body-error" :
undefined} and aria-invalid={!!bodyError} so the textarea is associated with and
reports the error state; keep the existing props and only add these
accessibility attributes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@components/subreddit-picker/CustomizePostDialog.tsx`:
- Around line 282-284: The body error message in CustomizePostDialog (the
conditional render using bodyError) is missing accessibility attributes; update
the <p> element that displays bodyError to include role="alert" (matching the
other error messages) so screen readers announce it immediately; locate the
conditional rendering that references the bodyError variable in the
CustomizePostDialog component and add role="alert" to that paragraph element.
- Around line 262-267: The error paragraph for bodyError is not announced to
screen readers and not linked to the textarea; update the error element rendered
in CustomizePostDialog to include an id (e.g., "body-error") and an
accessibility attribute such as role="alert" or aria-live="polite" (use the
existing conditional that renders {bodyError} to add these). Then update the
Textarea component (the one using bodyRef/customBody) to include
aria-describedby={bodyError ? "body-error" : undefined} and
aria-invalid={!!bodyError} so the textarea is associated with and reports the
error state; keep the existing props and only add these accessibility
attributes.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 8b1dbfa and f387180.

📒 Files selected for processing (1)
  • components/subreddit-picker/CustomizePostDialog.tsx

Temporarily disable the body required validation logic in the validateBody function. This change allows for further testing and adjustments without enforcing the body restriction policy. The commented-out code can be revisited for future implementation.

Made-with: Cursor
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dadf937903

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

});
continue;
}
// if (reqs.body_restriction_policy === 'required' && !body.trim()) {
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Reinstate BODY_REQUIRED in preflight validation

Commenting out this branch removes the only global check that blocks submissions when a subreddit requires a description, so validatePreflight can now return canProceed=true for empty bodies and the queue/review flow will allow posting until Reddit rejects it downstream. The new inline check in CustomizePostDialog does not cover this because it only runs if that dialog is opened (and customization is gated by paid/trial in pages/index.tsx), so free users and any non-customized subreddit path lose required-body protection entirely.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@lib/preflightValidation.ts`:
- Around line 275-286: Re-enable the server-side required-body validation in the
preflight routine by restoring the conditional that checks
reqs.body_restriction_policy === 'required' and empty body (body.trim() === ''),
and when triggered push the same issue object back onto issues (code:
'BODY_REQUIRED', severity: 'error', subreddit, message: `r/${subreddit} requires
a description`, suggestion: 'Add a description to your post', field: 'body',
expectedCategory: 'fixable_now') and then continue; locate this logic near the
validatePreflight / preflight validation loop that currently has the commented
block referencing reqs.body_restriction_policy and issues and restore it
unchanged so required-body policy is enforced server-side.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f387180 and dadf937.

📒 Files selected for processing (1)
  • lib/preflightValidation.ts

Comment on lines +275 to +286
// if (reqs.body_restriction_policy === 'required' && !body.trim()) {
// issues.push({
// code: 'BODY_REQUIRED',
// severity: 'error',
// subreddit,
// message: `r/${subreddit} requires a description`,
// suggestion: 'Add a description to your post',
// field: 'body',
// expectedCategory: 'fixable_now',
// });
// continue;
// }
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Restore server-side/preflight BODY_REQUIRED enforcement.

Line 275-Line 286 currently bypasses required-body validation by commenting out the check. This regresses preflight guarantees and allows invalid payloads to pass validatePreflight when subreddit policy requires a body.

🔧 Proposed fix
-    // Body required check
-    // if (reqs.body_restriction_policy === 'required' && !body.trim()) {
-    //   issues.push({
-    //     code: 'BODY_REQUIRED',
-    //     severity: 'error',
-    //     subreddit,
-    //     message: `r/${subreddit} requires a description`,
-    //     suggestion: 'Add a description to your post',
-    //     field: 'body',
-    //     expectedCategory: 'fixable_now',
-    //   });
-    //   continue;
-    // }
+    // Body required check
+    if (reqs.body_restriction_policy === 'required' && !body.trim()) {
+      issues.push({
+        code: 'BODY_REQUIRED',
+        severity: 'error',
+        subreddit,
+        message: `r/${subreddit} requires a description`,
+        suggestion: 'Add a description to your post',
+        field: 'body',
+        expectedCategory: 'fixable_now',
+      });
+      continue;
+    }

As per coding guidelines, "Never bypass validation" and "Always validate inputs."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@lib/preflightValidation.ts` around lines 275 - 286, Re-enable the server-side
required-body validation in the preflight routine by restoring the conditional
that checks reqs.body_restriction_policy === 'required' and empty body
(body.trim() === ''), and when triggered push the same issue object back onto
issues (code: 'BODY_REQUIRED', severity: 'error', subreddit, message:
`r/${subreddit} requires a description`, suggestion: 'Add a description to your
post', field: 'body', expectedCategory: 'fixable_now') and then continue; locate
this logic near the validatePreflight / preflight validation loop that currently
has the commented block referencing reqs.body_restriction_policy and issues and
restore it unchanged so required-body policy is enforced server-side.

- Install @vercel/analytics and add Analytics component to _app.tsx
- Improve checkout success page with payment confirmation polling
- Reduce auth revalidation interval to pick up post-payment webhook updates
- Add full product demo test spec

Made-with: Cursor
Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 30d813727d

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

}

try {
const { data } = await axios.get('/api/me');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Add timeout for /api/me poll requests

The new confirmation flow can block indefinitely when /api/me hangs, because the 30s max-duration check only runs before await axios.get('/api/me') and there is no request timeout; in that case the page stays on the spinner with no “Back to app” action exposed. This affects users on flaky/mobile networks where an XHR can stall without rejecting, so the poll loop never reaches the fallback path.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (2)
pages/checkout/success.tsx (1)

61-61: Convert to const arrow function export for consistency with project rules.

Switch export default function CheckoutSuccess() to const CheckoutSuccess = () => { ... }; export default CheckoutSuccess; to align with the project's style guidelines, which require const arrow functions instead of function declarations in TSX files.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pages/checkout/success.tsx` at line 61, Change the default exported function
declaration CheckoutSuccess to a const arrow function: replace the `export
default function CheckoutSuccess()` declaration with `const CheckoutSuccess = ()
=> { ... };` and then export it with `export default CheckoutSuccess;`, updating
any references inside the component body as-is to match the new const arrow
form.
tests/demo/full-product-demo.spec.ts (1)

5-79: Replace fixed pause() sleeps with condition-based waits to improve reliability and reduce execution time.

While this is a demo test where some delays may be intentional for visual/animation purposes, Playwright best practice is to replace arbitrary sleeps with UI-state waits. For example, instead of pause(1500) after clicking the review button, wait for the confirmation dialog or next expected UI element to appear using expect().toBeVisible(), toBeEnabled(), or waitForResponse(). This approach makes the test more reliable in CI and eliminates unnecessary slowdowns (the current pauses total ~10+ seconds).

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/demo/full-product-demo.spec.ts` around lines 5 - 79, The test uses many
fixed pause(ms) sleeps (pause, e.g., after goto, after expanding General, inside
the demoSubreddits loop, after switching to URL mode, after typing title, after
clicking the review button, and before assertions) which makes it flaky and
slow; replace each arbitrary pause with condition-based waits: use
expect(authenticatedPage.getByText(...)).toBeVisible()/toBeEnabled() or
authenticatedPage.waitForSelector()/waitForResponse() to wait for the exact UI
change or network response you expect (for example wait for the 'pics' text
after clicking the General category, wait for toggle button states inside the
demoSubreddits loop, wait for the URL/title input to be editable before typing,
wait for the review dialog or confirmation button instead of pause(1500), and
use waitForResponse or expect('All done!') visibility instead of the final
pauses), keeping the calls and helpers like setupMockRoutes and
setupQueueContractMock intact and only replacing pause(...) occurrences with the
appropriate conditional wait for the related element or response.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@pages/checkout/success.tsx`:
- Around line 28-30: The timeout branch in the polling logic currently sets
setReady(true) which shows a confirmed Pro state even when entitlement !==
'paid'; change it to not mark ready on timeout by removing setReady(true) and
instead set a distinct timeout state (e.g., setTimedOut(true) or
setPollingExpired(true)) so the UI can distinguish "timed out" vs "confirmed",
update the render logic to only show confirmed Pro when entitlement === 'paid'
(or isConfirmed flag) and show a timeout/error view when timedOut is true; apply
the same change to the duplicate polling block around the 105-136 area and
reference startRef, MAX_POLL_DURATION_MS, cancelled, setReady, and the
polling/effect function when making edits.

---

Nitpick comments:
In `@pages/checkout/success.tsx`:
- Line 61: Change the default exported function declaration CheckoutSuccess to a
const arrow function: replace the `export default function CheckoutSuccess()`
declaration with `const CheckoutSuccess = () => { ... };` and then export it
with `export default CheckoutSuccess;`, updating any references inside the
component body as-is to match the new const arrow form.

In `@tests/demo/full-product-demo.spec.ts`:
- Around line 5-79: The test uses many fixed pause(ms) sleeps (pause, e.g.,
after goto, after expanding General, inside the demoSubreddits loop, after
switching to URL mode, after typing title, after clicking the review button, and
before assertions) which makes it flaky and slow; replace each arbitrary pause
with condition-based waits: use
expect(authenticatedPage.getByText(...)).toBeVisible()/toBeEnabled() or
authenticatedPage.waitForSelector()/waitForResponse() to wait for the exact UI
change or network response you expect (for example wait for the 'pics' text
after clicking the General category, wait for toggle button states inside the
demoSubreddits loop, wait for the URL/title input to be editable before typing,
wait for the review dialog or confirmation button instead of pause(1500), and
use waitForResponse or expect('All done!') visibility instead of the final
pauses), keeping the calls and helpers like setupMockRoutes and
setupQueueContractMock intact and only replacing pause(...) occurrences with the
appropriate conditional wait for the related element or response.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between dadf937 and 30d8137.

⛔ Files ignored due to path filters (1)
  • package-lock.json is excluded by !**/package-lock.json
📒 Files selected for processing (5)
  • contexts/AuthContext.tsx
  • package.json
  • pages/_app.tsx
  • pages/checkout/success.tsx
  • tests/demo/full-product-demo.spec.ts
✅ Files skipped from review due to trivial changes (1)
  • package.json

Comment on lines +28 to +30
if (Date.now() - startRef.current > MAX_POLL_DURATION_MS) {
if (!cancelled) setReady(true);
return;
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Do not mark payment as confirmed on timeout.

When polling exceeds MAX_POLL_DURATION_MS, the code sets ready to true and renders a confirmed Pro success state even if /api/me never returned entitlement === 'paid'. This can produce false success UI.

Proposed fix (separate confirmed vs timeout states)
-const usePaymentConfirmation = () => {
-  const [ready, setReady] = useState(false);
+const usePaymentConfirmation = () => {
+  const [status, setStatus] = useState<'checking' | 'confirmed' | 'timeout'>('checking');
   const startRef = useRef(Date.now());
@@
-      if (Date.now() - startRef.current > MAX_POLL_DURATION_MS) {
-        if (!cancelled) setReady(true);
+      if (Date.now() - startRef.current > MAX_POLL_DURATION_MS) {
+        if (!cancelled) setStatus('timeout');
         return;
       }
@@
         if (data?.entitlement === 'paid') {
           if (!cancelled) {
             mutate(SWR_KEYS.AUTH, data, { revalidate: false });
-            setReady(true);
+            setStatus('confirmed');
           }
           return;
         }
@@
-  return ready;
+  return status;
 };
@@
-  const ready = usePaymentConfirmation();
+  const status = usePaymentConfirmation();
+  const ready = status === 'confirmed';

Also applies to: 105-136

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@pages/checkout/success.tsx` around lines 28 - 30, The timeout branch in the
polling logic currently sets setReady(true) which shows a confirmed Pro state
even when entitlement !== 'paid'; change it to not mark ready on timeout by
removing setReady(true) and instead set a distinct timeout state (e.g.,
setTimedOut(true) or setPollingExpired(true)) so the UI can distinguish "timed
out" vs "confirmed", update the render logic to only show confirmed Pro when
entitlement === 'paid' (or isConfirmed flag) and show a timeout/error view when
timedOut is true; apply the same change to the duplicate polling block around
the 105-136 area and reference startRef, MAX_POLL_DURATION_MS, cancelled,
setReady, and the polling/effect function when making edits.

Update the E2E flow tests to use the correct button selector pattern.
The ReviewPanel button text changed from "Post now" to "Post to N communities"
(e.g., "Post to 3 communities").

- Change selector regex from /post now/i to /post to \d+ communit/i
- Add dialog visibility wait before clicking the post button
- Fix mock streaming response format for queue processing
- Update selectSubreddits helper to handle pre-checked state
- Add entitlement mock data to bypass free user limits in tests

Made-with: Cursor
Copy link
Copy Markdown

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
tests/flows/helpers.ts (1)

125-180: Consider extracting shared streaming response builder.

This buildStreamResponse function duplicates the logic in buildQueueProcessStreamResponse from tests/mocks/handlers.ts (lines 166-238). Both construct identical streaming payloads with status, progress, result, waiting, and complete events.

Consider extracting a shared utility to reduce duplication and ensure consistency.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/flows/helpers.ts` around lines 125 - 180, The buildStreamResponse
function duplicates logic already present in buildQueueProcessStreamResponse;
extract a shared helper (e.g., createQueueStreamPayload or
buildProcessStreamEvents) and replace both buildStreamResponse and
buildQueueProcessStreamResponse to call that helper so
status/progress/result/waiting/complete event construction is centralized;
update tests to import/use the new utility and ensure it accepts parameters used
in both places (mockJobId, subreddits, outcomes, waitSeconds) and returns the
same newline-joined string.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@tests/flows/helpers.ts`:
- Around line 125-180: The buildStreamResponse function duplicates logic already
present in buildQueueProcessStreamResponse; extract a shared helper (e.g.,
createQueueStreamPayload or buildProcessStreamEvents) and replace both
buildStreamResponse and buildQueueProcessStreamResponse to call that helper so
status/progress/result/waiting/complete event construction is centralized;
update tests to import/use the new utility and ensure it accepts parameters used
in both places (mockJobId, subreddits, outcomes, waitSeconds) and returns the
same newline-joined string.

ℹ️ Review info

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 30d8137 and 53b6208.

📒 Files selected for processing (4)
  • tests/flows/core/core-flow.spec.ts
  • tests/flows/edge/edge-flow.spec.ts
  • tests/flows/helpers.ts
  • tests/mocks/handlers.ts

Copy link
Copy Markdown

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 53b6208d65

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread tests/flows/helpers.ts
})
);

return lines.join('\n');
Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Append trailing newline in mocked queue stream

The stream returned by setupQueueContractMock is built with lines.join('\n'), which leaves the final {"type":"complete"} record without a line terminator. useQueueJob parses updates by splitting on newlines and only consuming complete lines, so that last event stays buffered and never flips the queue to completed; flows that wait for completion UI (for example All done!) can stall or become flaky when this helper is used.

Useful? React with 👍 / 👎.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant