Skip to content

chore: fix race conditions, hydration, build issues#616

Open
merivercap wants to merge 1 commit intodevelopfrom
feat/devupdate
Open

chore: fix race conditions, hydration, build issues#616
merivercap wants to merge 1 commit intodevelopfrom
feat/devupdate

Conversation

@merivercap
Copy link
Contributor

@merivercap merivercap commented Feb 11, 2026

Overview

This PR addresses several stability and build issues encountered during development.

Changes

  • Hydration: Fixed hydration mismatches in Markdown and ChatMessagePro components to ensure consistent rendering.
  • Race Conditions: Resolved race conditions in useWorkspaceChat hooks to improve chat reliability.
  • Build: Updated next.config.ts and tsconfig.json to fix build errors and optimize configuration.
  • Types: Added react-markdown-patch.d.ts to resolve missing type definitions.
  • Testing: Updated integration tests to reflect these changes.

Verification

  • Build passes locally
  • hydration errors resolved in console
  • Chat race conditions mitigated

Summary by Sourcery

Improve chat stability, markdown rendering, and build configuration while updating seeds and documenting a planned chat refactor.

Bug Fixes:

  • Add retry logic around assistant answer ingestion and workspace document upload to mitigate race conditions with thread creation.
  • Fix signup preference creation by using the correct preferences insert API response and error handling.
  • Prevent React Markdown components from receiving undefined content and adjust plugin configuration to avoid hydration/type issues.
  • Address test and lint issues in chat and scope selection tests by tightening types and suppressing intentional any usage where appropriate.

Enhancements:

  • Refine prompt details input initialization using Object.fromEntries for clearer default input mapping.
  • Simplify admin preference and organization insertion by removing redundant user existence checks.
  • Adjust onboarding time initialization to avoid server/client timestamp mismatches.
  • Relax markdown table component typing to align with react-markdown v8 and existing component implementations.
  • Extend document thread outline and onboarding components to handle missing descriptions more defensively.

Build:

  • Add workspace package path aliases and configure Next.js to transpile internal mb-* packages for compatibility with Next 15 and React 19.
  • Downgrade react-markdown and related remark/rehype math plugins to a compatible version and add a patch type declaration to work with React 19/Next 15.
  • Update Hasura seed application Task to target the masterbots database explicitly.

Deployment:

  • Refresh Hasura Git LFS seed pointers for users, threads, messages, enums, tags, categories, and examples to align with the current masterbots dataset.

Documentation:

  • Add a detailed Phase_0 chat refactor architecture document describing the nested accordion chat design and related data flow.

Tests:

  • Update workspace chat and scope window tests to match new typing and behavior and to capture the latest chat context semantics.

Chores:

  • Add seed and error log artifacts to the repository for debugging Hasura seeding issues.

Summary by CodeRabbit

  • New Features

    • Added nested accordion interface for organizing document thread conversations by section.
    • Enhanced markdown rendering with improved support for mathematical equations and tables.
  • Bug Fixes

    • Fixed rendering issues when chatbot descriptions are missing.
    • Improved handling of transient data availability issues in document threads.
    • Enhanced resilience for database operations during ingestion.
  • Improvements

    • Optimized markdown plugin pipeline for better content display.

@vercel
Copy link

vercel bot commented Feb 11, 2026

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

Project Deployment Actions Updated (UTC)
masterbots Ready Ready Preview, Comment Feb 11, 2026 0:40am
masterbots-pro Ready Ready Preview, Comment Feb 11, 2026 0:40am

Request Review

@sourcery-ai
Copy link

sourcery-ai bot commented Feb 11, 2026

Reviewer's Guide

Adds retry logic and race-condition mitigation for thread-related DB operations, adjusts signup preference creation to match Hasura API, downgrades markdown/math packages and wiring to fix hydration issues, updates Next/TS config and paths for workspace packages, and tweaks tests, seeds, and markdown usage to align with the new behavior and typings.

Class diagram for JSX type patch and MemoizedReactMarkdown usage

classDiagram
    class ReactJSXIntrinsicElements {
    }

    class JSXIntrinsicElements {
    }

    class JSXNamespace {
    }

    class MemoizedReactMarkdown {
        +Options props
        +render()
    }

    class RemarkMath {
    }

    class RehypeKatex {
    }

    class ReactMarkdownCore {
    }

    JSXNamespace <|-- JSXIntrinsicElements : contains
    JSXIntrinsicElements ..|> ReactJSXIntrinsicElements : extends

    MemoizedReactMarkdown --> ReactMarkdownCore : wraps
    MemoizedReactMarkdown --> RemarkMath : remarkPlugins
    MemoizedReactMarkdown --> RehypeKatex : rehypePlugins
Loading

File-Level Changes

Change Details Files
Add resilient retry logic around assistant answer ingestion and workspace document upload to handle FK and thread creation race conditions.
  • Wrap assistantAnswers insert in ingestAssistantAnswer with a bounded exponential backoff retry loop on Postgres FK violation (code 23503).
  • Add retry loop in uploadWorkspaceDocumentToBucket that repeatedly calls getThreadBySlug until a thread is found or retries exhaust.
apps/pro-web/app/actions/chat-memory/ingest-assistant-answer.ts
apps/pro-web/app/actions/thread.actions.ts
Align subscription prompt inputs handling and signup preference creation with current APIs and error handling.
  • Replace manual reduce with Object.fromEntries for constructing inputs map from prompt inputs.
  • Switch signup route to use insertPreferencesByUserId, checking for returned data and error instead of insertAdminUserPreferences.
  • Remove verifyUserExists pre-checks from insertAdminUserPreferences and insertUserOrganizations to avoid redundant lookups.
apps/pro-web/app/actions/subscriptions.actions.ts
apps/pro-web/app/api/auth/signup/route.ts
apps/pro-web/app/actions/admin.actions.ts
Fix React markdown/math integration and hydration issues by adjusting dependencies, plugin wiring, and defensive content handling, plus adding a JSX typings patch.
  • Downgrade react-markdown and associated remark/rehype math packages to versions compatible with React 19/Next 15.
  • Update ChatMessagePro, ImageMessageComponent, and onboarding/browse views to separate remarkPlugins and rehypePlugins correctly and to guard against undefined description/content values.
  • Tighten memoizedMarkdownComponents typing by casting the components map to Components with ts-ignore for table/th.
  • Centralize math markdown support in shared MemoizedReactMarkdown with explicit ts-expect-error annotations for type incompatibilities.
  • Add react-markdown-patch.d.ts to restore JSX.IntrinsicElements for react-markdown v8 under React 19.
apps/pro-web/package.json
apps/pro-web/components/routes/pro/chat-message-pro.tsx
apps/pro-web/components/shared/image-message.tsx
apps/pro-web/components/routes/browse/browse-chatbot-desktop-details.tsx
apps/pro-web/components/routes/browse/browse-chatbot-mobile-details.tsx
apps/pro-web/components/routes/chat/chat-selected-chatbot-mobile.tsx
apps/pro-web/components/routes/chat/onboarding-chatbot-details.tsx
apps/pro-web/components/shared/onboarding-chatbot-card.tsx
apps/pro-web/components/shared/markdown.tsx
apps/pro-web/lib/memoized-markdown-components.tsx
apps/pro-web/types/react-markdown-patch.d.ts
Improve robustness and typings in tests and onboarding UI to satisfy linting and hydration, and to better capture workspace chat behavior.
  • Adjust select-scope-conversation-window tests to pass docNodeId where needed and cast nullable fields via any/unknown to satisfy type expectations.
  • Add biome-ignore comments for intentional any usage in tests and mocks related to use-workspace-chat, and ensure getCanonicalDocNodeId mocks are typed.
  • Initialize onboarding panel now state to 0 and set it within useEffect to avoid hydration mismatch.
  • Minor cleanup such as removing unnecessary biome-ignore and ensuring last* message expectations cast through any.
apps/pro-web/lib/select-scope-conversation-window.test.ts
apps/pro-web/components/routes/pro/onboarding-panel.tsx
apps/pro-web/lib/hooks/use-workspace-chat.ask.test.tsx
apps/pro-web/lib/hooks/use-workspace-chat.edit.test.tsx
apps/pro-web/lib/hooks/use-workspace-chat.rag.test.tsx
apps/pro-web/lib/hooks/use-workspace-chat.integration.test.tsx
apps/pro-web/lib/chat/chat-context-utils.ts
Update build configuration, module resolution, and tooling for workspace packages and Hasura seeds.
  • Add transpilePackages for mb-* workspace libraries in next.config.ts to ensure they are compiled correctly by Next.js.
  • Extend tsconfig.json paths to point to mb-ui, mb-lib, mb-types, mb-genql, and mb-env package entrypoints.
  • Change Taskfile seed command to pass explicit --database-name masterbots.
  • Update Git LFS pointers for multiple Hasura seed files and add seed logs for debugging.
  • Add Phase_0_Chat_Refactor.md architecture document and seed_error.log as repo artifacts.
apps/pro-web/next.config.ts
apps/pro-web/tsconfig.json
Taskfile.yml
apps/hasura/seeds/masterbots/*.sql
bun.lock
seed.log
Phase_0_Chat_Refactor.md
seed_error.log
Minor UI and helper cleanups to reduce noise and align with current patterns.
  • Simplify BotPage to directly render BotProfileThreadSection without extra fragment/biome ignore.
  • Ensure chat description markdown renderers use fallback empty strings to avoid runtime errors.
  • Tidy chat-context-utils by removing an unnecessary biome-ignore comment on passthrough metadata.
apps/pro-web/app/b/page.tsx
apps/pro-web/components/routes/pro/chat-message-pro.tsx
apps/pro-web/components/routes/browse/browse-chatbot-desktop-details.tsx
apps/pro-web/components/routes/browse/browse-chatbot-mobile-details.tsx
apps/pro-web/components/routes/chat/chat-selected-chatbot-mobile.tsx
apps/pro-web/components/routes/chat/onboarding-chatbot-details.tsx
apps/pro-web/components/shared/onboarding-chatbot-card.tsx
apps/pro-web/lib/chat/chat-context-utils.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

Hey - I've found 1 issue, and left some high level feedback:

  • In getPromptDetails the catch block logs error but the caught variable is named err, so the console.error is currently referencing an undefined identifier; switch to logging err (or rename the parameter) to avoid masking real failures.
  • The insertPreferencesByUserId call in the signup route still has a multi-line inline comment about its signature and omits the jwt argument it mentions; consider either updating the comment to reflect the current API or passing the required parameters so the implementation and commentary stay in sync.
  • You’ve added seed.log and seed_error.log to the repo; if these are runtime artefacts rather than canonical seed inputs, it may be better to remove them from version control and add them to .gitignore to avoid noisy diffs.
Prompt for AI Agents
Please address the comments from this code review:

## Overall Comments
- In `getPromptDetails` the `catch` block logs `error` but the caught variable is named `err`, so the console.error is currently referencing an undefined identifier; switch to logging `err` (or rename the parameter) to avoid masking real failures.
- The `insertPreferencesByUserId` call in the signup route still has a multi-line inline comment about its signature and omits the `jwt` argument it mentions; consider either updating the comment to reflect the current API or passing the required parameters so the implementation and commentary stay in sync.
- You’ve added `seed.log` and `seed_error.log` to the repo; if these are runtime artefacts rather than canonical seed inputs, it may be better to remove them from version control and add them to `.gitignore` to avoid noisy diffs.

## Individual Comments

### Comment 1
<location> `apps/pro-web/app/actions/subscriptions.actions.ts:205-206` </location>
<code_context>
+				}[]
+			).map((input) => [input.label, '']),
 		)
 	} catch (err) {
 		console.error('Error fetching prompt details:', error)
</code_context>

<issue_to_address>
**issue (bug_risk):** The catch block logs an undefined `error` variable instead of the caught `err`.

In this catch block, `err` is the caught exception, but `console.error` references `error`, which is undefined in this scope and will throw a `ReferenceError`, masking the real issue. Use `err` in the log call instead.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

Comment on lines 205 to 206
} catch (err) {
console.error('Error fetching prompt details:', error)
Copy link

Choose a reason for hiding this comment

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

issue (bug_risk): The catch block logs an undefined error variable instead of the caught err.

In this catch block, err is the caught exception, but console.error references error, which is undefined in this scope and will throw a ReferenceError, masking the real issue. Use err in the log call instead.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Feb 11, 2026

📝 Walkthrough

Walkthrough

This PR introduces a comprehensive nested accordion-based document thread outline UI system with associated data models and rendering pipelines, adds retry-based resilience to async operations, downgrades markdown-related dependencies, establishes new TypeScript path aliases, and applies bug fixes for undefined value handling across markdown rendering components.

Changes

Cohort / File(s) Summary
Document Thread Outline Refactor
apps/pro-web/lib/markdown-outline.ts, apps/pro-web/lib/markdown-utils.ts, apps/pro-web/lib/simple-rag/document-thread-grouping.ts, apps/pro-web/lib/threads.ts, apps/pro-web/components/routes/workspace/document-tab/document-thread-outline.tsx, apps/pro-web/components/routes/workspace/document-tab/section-subaccordion-row.tsx
Introduces OutlineNode, MarkdownSection, MessagePair public types and three grouping/normalization functions (groupMessagePairsByScope, normalizePairsForDisplay, extractScopeInfo). Adds DocumentThreadOutline and SectionSubaccordionRow components with scope-based message organization, orphan handling, and recursive accordion rendering.
Hasura Database Seeds
apps/hasura/seeds/masterbots/*_*.sql (23 files)
Git LFS pointer metadata updates only; oid and size fields updated across all seed files with no functional SQL content changes.
Async Resilience & Retry Logic
apps/pro-web/app/actions/chat-memory/ingest-assistant-answer.ts, apps/pro-web/app/actions/thread.actions.ts
Added retry loops with exponential backoff (max 5 attempts) for foreign key violation handling during ingestion and thread lookup operations.
Markdown Plugin & Rendering
apps/pro-web/components/shared/markdown.tsx, apps/pro-web/lib/memoized-markdown-components.tsx, apps/pro-web/components/shared/image-message.tsx, apps/pro-web/components/routes/pro/chat-message-pro.tsx, apps/pro-web/components/routes/browse/browse-chatbot-*.tsx, apps/pro-web/components/routes/chat/...-details.tsx, apps/pro-web/components/shared/onboarding-chatbot-card.tsx
Reorganized markdown rendering plugins (remarkMath, rehypeKatex added to markdown.tsx; rehypeMathJax moved from remark to rehype plugins). Added fallback empty strings (
Dependencies & Configuration
apps/pro-web/package.json, apps/pro-web/next.config.ts, apps/pro-web/tsconfig.json, apps/pro-web/types/react-markdown-patch.d.ts
Downgraded markdown-related packages (react-markdown, rehype-katex, remark-math, etc.), added transpilePackages config for monorepo packages, added TypeScript path aliases for mb-* packages, and added React 19/Next 15 compatibility patch for react-markdown v8.
User Preferences Migration
apps/pro-web/app/api/auth/signup/route.ts, apps/pro-web/app/actions/admin.actions.ts
Replaced insertAdminUserPreferences with insertPreferencesByUserId in signup flow; removed user existence pre-checks in admin preferences and organization insertion.
Object Construction Refactoring
apps/pro-web/app/actions/subscriptions.actions.ts
Replaced reduce-based object construction with Object.fromEntries/map pattern.
Test & Code Quality
apps/pro-web/lib/hooks/use-workspace-chat.*.test.tsx, apps/pro-web/lib/select-scope-conversation-window.test.ts
Added biome-ignore lint comments in test mocks and assertions; adjusted test type casts (as any) for dynamic typing and explicit null casts for test scenarios.
Minor Cleanups
apps/pro-web/app/b/page.tsx, apps/pro-web/lib/chat/chat-context-utils.ts, apps/pro-web/components/routes/pro/onboarding-panel.tsx
Simplified JSX return statements, removed inline comments, and refactored state initialization with explicit immediate timestamp update.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested labels

bug, chore, frontend

Suggested reviewers

  • AndlerRL
  • Bran18

Poem

🐰 A accordion unfolds with nested delight,
Messages grouped by scope, rendered just right,
Markdown retouched with math in the mix,
Retry loops guard against quirky conflicts,
Dependencies shift as the codebase now flows! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1
❌ Failed checks (1 warning)
Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% 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 concisely summarizes the main changes: fixing race conditions, hydration issues, and build problems. It accurately reflects the core objectives mentioned in the PR summary.

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

✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch feat/devupdate

Tip

Issue Planner is now in beta. Read the docs and try it out! Share your feedback on Discord.


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
Contributor

@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: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
apps/pro-web/app/api/auth/signup/route.ts (2)

129-142: ⚠️ Potential issue | 🟡 Minor

Remove developer thinking notes from production code.

Lines 130–134 contain internal reasoning comments ("Wait, let me check…") that read like debug notes rather than documentation. They should be cleaned up before merging.

Proposed fix
 			const { data: preference, error } = await insertPreferencesByUserId({
-				// userId is not needed in the object for this specific function signature in hasura.service,
-				// check the definition of insertPreferencesByUserId manually?
-				// Wait, let me check the signature of insertPreferencesByUserId again.
-				// It takes { jwt, preferencesSet }. preferencesSet is PreferenceInsertInput.
-				// PreferenceInsertInput has userId.
 				preferencesSet: {
 					userId: insertUserOne.userId,
 					preferredComplexity: 'general',
 					preferredLength: 'detailed',
 					preferredTone: 'neutral',
 					preferredType: 'mix',
 				},
 			})

129-142: ⚠️ Potential issue | 🔴 Critical

Fix the pro-web insertPreferencesByUserId mutation return shape and use valid enum values.

Two confirmed issues prevent user signup in pro-web:

  1. Invalid mutation return shape: The function selects preferences: { returning: { __scalar: true } }, but the Preference return type has no preferences field. It should select individual fields like the web version does: lang: true, fontSize: true, preferenceId: true. The current selection will fail with a GraphQL query error.

  2. Invalid enum values: The defaults use 'general' and 'mix', but the database enum tables only contain:

    • complexity_enum: expert, adult, eli5 (not 'general')
    • type_enum: narrative, step_by_step, bullet_points, neutral (not 'mix')

    These FK constraint violations will cause the insert to fail at the database level. Use valid enum values: preferredComplexity: 'eli5' (or 'expert'/'adult') and preferredType: 'narrative' (or 'step_by_step'/'bullet_points'/'neutral').

🤖 Fix all issues with AI agents
In `@apps/pro-web/lib/select-scope-conversation-window.test.ts`:
- Around line 297-306: Update the ScopeConversationWindow type so lastUser and
lastAssistant are typed as Message (not Message | UIMessage): replace the union
in the declaration of ScopeConversationWindow (fields lastUser, lastAssistant)
to use Message directly and adjust any imports to remove UIMessage if no longer
used; ensure userQuestions remains Array<Message> so callers/tests can access
messageId without casting.

In `@apps/pro-web/package.json`:
- Around line 94-101: Update the markdown deps and reconcile math renderers:
change remark-math from 3.0.1 to 5.1.1 in apps/pro-web/package.json to remove
the type incompatibility that required the `@ts-expect-error` in
apps/pro-web/components/shared/markdown.tsx (look for the MemoizedReactMarkdown
usage), then run install and remove the `@ts-expect-error` in that file if types
are satisfied; also decide whether to standardize on rehype-katex or
rehype-mathjax by either removing the unused rehype-mathjax@4.0.0 dependency or
integrating it into the main MemoizedReactMarkdown pipeline (replace
rehype-katex usage or add rehype-mathjax to the same plugins list) so math
rendering is consistent across chat components and the main markdown renderer.

In `@Phase_0_Chat_Refactor.md`:
- Around line 7-15: The document contains broken citation link fragments like
[0-cite-N](`#0-cite-N`) across multiple sections (e.g., in definitions for
OutlineNode, MarkdownSection, MessagePair, Scope/ScopeId, and Level vs Depth);
fix by either adding matching anchor targets (e.g., create corresponding
headings or anchor IDs named 0-cite-0, 0-cite-1, etc.) or replacing each inline
link with a plain-text citation (e.g., “see citation 0-cite-0”) for the
referenced concepts (OutlineNode, MarkdownSection, MessagePair, Scope/ScopeId,
Level vs Depth) so the references resolve correctly.
🧹 Nitpick comments (9)
apps/pro-web/lib/select-scope-conversation-window.test.ts (1)

207-208: null as unknown as string double-cast is acceptable for edge-case testing, but consider a helper.

The triple repetition of null as unknown as string could be extracted into a small constant (e.g., const NULL_SCOPE = null as unknown as string) at the top of the describe block, next to ROOT and SECTION, to reduce noise and make intent clearer.

♻️ Suggested constant extraction
 const ROOT = 'doc-root-1'
 const SECTION = 'heading-1'
+const NULL_SCOPE = null as unknown as string

Then replace all three occurrences:

-			scopeId: null as unknown as string,
+			scopeId: NULL_SCOPE,

Also applies to: 223-224, 274-274

apps/pro-web/app/b/page.tsx (1)

4-6: Unused props parameter.

props (typed as PageProps) is declared but never referenced in the function body. If the page doesn't need route params/searchParams, consider removing it to avoid dead code.

Suggested fix
-export default async function BotPage(props: PageProps) {
+export default async function BotPage() {
 	// When no bot is selected, pass null/undefined to show welcome view
 	return <BotProfileThreadSection threads={[]} count={0} chatbot={null} />
 }
apps/pro-web/components/routes/chat/chat-selected-chatbot-mobile.tsx (1)

94-94: Redundant default export alongside named export.

SelectedBotMobileView is already a named export on line 15. The default export on line 94 is unnecessary and goes against the project's preference for named exports. As per coding guidelines: "Avoid default exports; prefer named exports to make imports clearer and help avoid naming conflicts."

Suggested fix
 }
-
-export default SelectedBotMobileView
apps/pro-web/app/actions/thread.actions.ts (1)

333-350: Retry loop is reasonable but total worst-case latency (~15s) is worth noting.

The exponential backoff (1s → 2s → 4s → 8s) totals ~15 seconds before the final attempt. For a server action, this could approach timeout thresholds or noticeably degrade UX. Consider whether fewer retries or a shorter base delay would suffice, or whether the root cause (thread not yet persisted when this runs) can be addressed upstream with a more deterministic signal.

Also, the console.warn only logs intermediate retry attempts. Adding a final warning before the throw on Line 350 would help with debugging production failures.

Suggested improvement
 	}
 
-	if (!existingThread) throw new Error('Thread not found for slug')
+	if (!existingThread) {
+		console.error(
+			`[uploadWorkspaceDocumentToBucket] Thread not found for slug ${threadSlug} after ${MAX_RETRIES} attempts.`,
+		)
+		throw new Error('Thread not found for slug')
+	}
apps/pro-web/components/shared/image-message.tsx (1)

31-35: Caller-supplied plugins override MemoizedReactMarkdown's built-in plugins.

MemoizedReactMarkdown now hardcodes remarkMath + rehypeKatex internally (in markdown.tsx), but the {...props} spread overwrites them. This means this component gets remarkGfm + rehypeMathJax while MemoizedReactMarkdown elsewhere uses remarkGfm + remarkMath + rehypeKatex — two different math rendering stacks (MathJax vs KaTeX).

If this is intentional, consider adding a brief comment explaining why this component uses a different math pipeline. If not, consider dropping the explicit plugin props here and relying on the shared defaults.

apps/pro-web/components/shared/markdown.tsx (1)

10-18: transformLatexBlocks converts inline math \(...\) to display math $$...$$.

Since singleDollarTextMath: false disables single-$ parsing, there's no way to produce inline math — both \[...\] and \(...\) end up as $$...$$ (display/block). If inline math rendering matters, consider mapping \(...\) to $...$ and enabling singleDollarTextMath, or using a different delimiter strategy. This appears to be pre-existing behavior, so it can be deferred.

apps/pro-web/app/actions/chat-memory/ingest-assistant-answer.ts (1)

64-70: Pre-existing race: nextTurnIndex computed outside the retry loop.

If multiple concurrent ingest calls target the same threadId while the thread doesn't yet exist, they'll all compute nextTurnIndex = 1 (since findFirst returns nothing). Once the thread appears and retries succeed, all inserts land with turnIndex = 1. There's no unique constraint on (threadId, turnIndex), so the DB accepts them, but the logical ordering is lost.

This isn't introduced by this PR, but if turn ordering matters, consider either:

  • Moving the nextTurnIndex query inside the retry loop, or
  • Using a DB sequence / SELECT MAX(...) + 1 inside a transaction.
apps/pro-web/app/api/auth/signup/route.ts (1)

2-9: Unused import: sendEmailVerification.

sendEmailVerification (line 3) is imported but never called — the verification flow at lines 173-190 generates a token but returns before sending an email. This appears to be pre-existing dead code, but worth noting for cleanup.

Phase_0_Chat_Refactor.md (1)

1-1: File name doesn't follow the repository's naming convention.

The coding guidelines specify lowercase with dash separators for file names. Phase_0_Chat_Refactor.md should be renamed to phase-0-chat-refactor.md. As per coding guidelines: "Use lowercase with dash separators for directory and file names (e.g., components/auth-wizard)".

Comment on lines +297 to +306
expect(res.userQuestions.map((m) => (m as any).messageId)).toEqual([
'u1',
'u2',
])

// lastAssistant: latest assistant message
expect(res.lastAssistant?.messageId).toBe('a1')
expect((res.lastAssistant as any)?.messageId).toBe('a1')

// lastUser: latest user message even if excluded from q-chain
expect(res.lastUser?.messageId).toBe('u3')
expect((res.lastUser as any)?.messageId).toBe('u3')
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

fd "select-scope-conversation-window" --type f

Repository: bitcashorg/masterbots

Length of output: 122


🏁 Script executed:

fd "select-scope-conversation-window" --type f | grep -v test

Repository: bitcashorg/masterbots

Length of output: 47


🏁 Script executed:

# Search for the function definition in the codebase
rg "selectScopeConversationWindow" --type ts --type tsx -l

Repository: bitcashorg/masterbots

Length of output: 92


🏁 Script executed:

rg "selectScopeConversationWindow" --type ts -l

Repository: bitcashorg/masterbots

Length of output: 456


🏁 Script executed:

# Also search for the function definition without type restrictions
rg "function selectScopeConversationWindow|const selectScopeConversationWindow|export.*selectScopeConversationWindow"

Repository: bitcashorg/masterbots

Length of output: 194


🏁 Script executed:

cat -n apps/pro-web/app/actions/chat-memory/get-scope-conversation-window.ts

Repository: bitcashorg/masterbots

Length of output: 6862


🏁 Script executed:

rg "type Message" apps/pro-web --type ts -A 10 | head -50

Repository: bitcashorg/masterbots

Length of output: 3218


🏁 Script executed:

# Look for mb-genql types
find apps/pro-web -name "*mb-genql*" -o -name "*generated*" -type f | head -20

Repository: bitcashorg/masterbots

Length of output: 115


🏁 Script executed:

# Check the Message type structure in the codebase
rg "messageId" apps/pro-web/components/routes/browse/browse-chat-messages.tsx -B 2 -A 2

Repository: bitcashorg/masterbots

Length of output: 209


🏁 Script executed:

# Look at the test file to understand the exact issue
sed -n '297,306p' apps/pro-web/lib/select-scope-conversation-window.test.ts

Repository: bitcashorg/masterbots

Length of output: 383


🏁 Script executed:

# Check the full test context to understand what the function should return
sed -n '280,310p' apps/pro-web/lib/select-scope-conversation-window.test.ts

Repository: bitcashorg/masterbots

Length of output: 893


🏁 Script executed:

# Check what other uses of selectScopeConversationWindow expect
rg "selectScopeConversationWindow" apps/pro-web -A 5 -B 2 | grep -v "test.ts" | head -40

Repository: bitcashorg/masterbots

Length of output: 2120


🏁 Script executed:

# Check how the window result is used in use-workspace-chat.tsx
rg "window\." apps/pro-web/lib/hooks/use-workspace-chat.tsx -B 2 -A 2 | head -50

Repository: bitcashorg/masterbots

Length of output: 503


🏁 Script executed:

# Check how it's used in chat-context-utils.ts
rg "selectScopeConversationWindow" apps/pro-web/lib/chat/chat-context-utils.ts -A 15 | head -40

Repository: bitcashorg/masterbots

Length of output: 1167


🏁 Script executed:

# Check the Message type definition from mb-genql more closely
rg "from 'mb-genql'" apps/pro-web/services/hasura/hasura.service.ts -B 5 -A 20 | head -60

Repository: bitcashorg/masterbots

Length of output: 539


🏁 Script executed:

# Check if there's a type definition file for Message
find apps/pro-web -name "*.type.ts" -o -name "types.ts" | xargs grep -l "Message" 2>/dev/null | head -5

Repository: bitcashorg/masterbots

Length of output: 116


🏁 Script executed:

# Check the message type definition in the service type file
cat apps/pro-web/services/hasura/hasura.service.type.ts | head -100

Repository: bitcashorg/masterbots

Length of output: 2321


🏁 Script executed:

# Also check what Message looks like when imported from mb-genql
rg "type Message|interface Message" --type ts -B 2 -A 10 | grep -A 10 "mb-genql" | head -30

Repository: bitcashorg/masterbots

Length of output: 2034


🏁 Script executed:

# Get the full Message interface definition
rg "export interface Message \{" packages/mb-genql/generated/schema.ts -A 30 | head -40

Repository: bitcashorg/masterbots

Length of output: 1208


🏁 Script executed:

# Check what UIMessage looks like from `@ai-sdk/react`
rg "import.*UIMessage" apps/pro-web --type ts -B 2 -A 5 | head -20

Repository: bitcashorg/masterbots

Length of output: 1704


🏁 Script executed:

# Check the actual return type used in practice - look at the cast in selectScopeConversationWindow
sed -n '170,185p' apps/pro-web/app/actions/chat-memory/get-scope-conversation-window.ts

Repository: bitcashorg/masterbots

Length of output: 538


Update return type to exclude UIMessage union—the function always returns Message which includes messageId.

The ScopeConversationWindow type declares lastUser and lastAssistant as Message | UIMessage, but the function always returns Message instances (see lines 177–179). Since UIMessage from the ai package lacks messageId, the union forces callers and tests to cast to Message or any to access messageId. This is unnecessary and creates a false type safety gap.

The query explicitly selects messageId, and the Message type from mb-genql declares it as a required field. Change the ScopeConversationWindow type definition to use Message directly instead of the union:

export type ScopeConversationWindow = {
  lastUser?: Message
  lastAssistant?: Message
  userQuestions: Array<Message>
}

This eliminates the type-safety workaround and makes the actual return contract explicit.

🤖 Prompt for AI Agents
In `@apps/pro-web/lib/select-scope-conversation-window.test.ts` around lines 297 -
306, Update the ScopeConversationWindow type so lastUser and lastAssistant are
typed as Message (not Message | UIMessage): replace the union in the declaration
of ScopeConversationWindow (fields lastUser, lastAssistant) to use Message
directly and adjust any imports to remove UIMessage if no longer used; ensure
userQuestions remains Array<Message> so callers/tests can access messageId
without casting.

Comment on lines +94 to +101
"react-markdown": "8.0.7",
"react-syntax-highlighter": "^15.6.1",
"react-textarea-autosize": "^8.5.7",
"react-use": "^17.6.0",
"rehype-katex": "^7.0.1",
"rehype-mathjax": "^7.1.0",
"remark-gfm": "4.0.1",
"remark-math": "^6.0.0",
"rehype-katex": "6.0.3",
"rehype-mathjax": "4.0.0",
"remark-gfm": "3.0.1",
"remark-math": "3.0.1",
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

# Check how remark-math and related packages are used
rg -n "remark-math|rehype-mathjax|rehype-katex|math" --type ts --type tsx -B2 -A2 2>/dev/null | head -100

# Check if there are any version compatibility notes in comments or docs
fd "README|CHANGELOG|NOTES" --type f | xargs grep -l "remark-math\|rehype-mathjax" 2>/dev/null || echo "No compatibility notes found"

# Check package-lock or lock files for dependency resolution info
fd "package-lock.json|pnpm-lock.yaml|yarn.lock|bun.lockb" --type f 2>/dev/null | head -5

Repository: bitcashorg/masterbots

Length of output: 93


🏁 Script executed:

# Check the current package.json to see if there are any comments or notes about the downgrades
sed -n '90,110p' apps/pro-web/package.json

Repository: bitcashorg/masterbots

Length of output: 637


🏁 Script executed:

# Look for where these plugins are configured in the code
rg -n "usePlugins|Plugin|remark|rehype" --type ts --type tsx -g "*/markdown*" -g "*/react-markdown*" -B2 -A2 2>/dev/null | head -80

Repository: bitcashorg/masterbots

Length of output: 47


🏁 Script executed:

# Check if there's a components using react-markdown with the plugins
fd -e tsx -e ts | xargs grep -l "react-markdown" 2>/dev/null | head -10

Repository: bitcashorg/masterbots

Length of output: 289


🏁 Script executed:

# Check the markdown component implementations
cat -n apps/pro-web/components/shared/markdown.tsx

Repository: bitcashorg/masterbots

Length of output: 1707


🏁 Script executed:

# Check the memoized markdown components
cat -n apps/pro-web/lib/memoized-markdown-components.tsx

Repository: bitcashorg/masterbots

Length of output: 7573


🏁 Script executed:

# Check the react-markdown patch - this is important!
cat -n apps/pro-web/types/react-markdown-patch.d.ts

Repository: bitcashorg/masterbots

Length of output: 421


🏁 Script executed:

# Check if rehype-mathjax is actually used in the codebase
rg -n "rehype-mathjax|rehypeMathJax" --type ts --type tsx

Repository: bitcashorg/masterbots

Length of output: 92


🏁 Script executed:

# Verify the exact versions currently in package.json
grep -A2 -B2 "rehype-katex\|rehype-mathjax\|remark-math" apps/pro-web/package.json

Repository: bitcashorg/masterbots

Length of output: 287


🏁 Script executed:

# Check if rehype-mathjax is used anywhere
rg -n "rehype-mathjax|mathJax" -g "*.ts" -g "*.tsx"

Repository: bitcashorg/masterbots

Length of output: 350


🏁 Script executed:

# Also check JavaScript files
rg -n "rehype-mathjax" --type js

Repository: bitcashorg/masterbots

Length of output: 47


🏁 Script executed:

# Check the entire apps/pro-web directory for any rehype-mathjax usage
find apps/pro-web -type f \( -name "*.ts" -o -name "*.tsx" -o -name "*.js" -o -name "*.jsx" \) -exec grep -l "rehype-mathjax" {} \;

Repository: bitcashorg/masterbots

Length of output: 169


🏁 Script executed:

# Check how rehype-mathjax is used in chat-message-pro.tsx
cat -n apps/pro-web/components/routes/pro/chat-message-pro.tsx | head -50

Repository: bitcashorg/masterbots

Length of output: 2420


🏁 Script executed:

# Check how rehype-mathjax is used in image-message.tsx
cat -n apps/pro-web/components/shared/image-message.tsx | head -50

Repository: bitcashorg/masterbots

Length of output: 1949


🏁 Script executed:

# Search for where rehypeMathJax is actually passed to plugins
rg -n "rehypeMathJax|rehype-mathjax" -B5 -A5 -g "*.ts" -g "*.tsx"

Repository: bitcashorg/masterbots

Length of output: 6367


Remark-math v3.0.1 causes documented type incompatibilities — use v5.1.1 as validated in prior work.

The markdown component has @ts-expect-error - remark-math 3 types incompatible with react-markdown 8 (line 26 in apps/pro-web/components/shared/markdown.tsx), confirming the type issues with v3.0.1. Prior learning documented that v5.1.1 was the validated stable downgrade, and the current further downgrade to v3.0.1 introduces suppressions that mask type safety.

Additionally, rehype-mathjax@4.0.0 is imported in chat components but not integrated into the main MemoizedReactMarkdown pipeline, which uses rehype-katex instead. This creates inconsistency in math rendering engines.

Update remark-math to 5.1.1 and verify whether rehype-mathjax should be removed or properly integrated with the main markdown rendering stack.

🤖 Prompt for AI Agents
In `@apps/pro-web/package.json` around lines 94 - 101, Update the markdown deps
and reconcile math renderers: change remark-math from 3.0.1 to 5.1.1 in
apps/pro-web/package.json to remove the type incompatibility that required the
`@ts-expect-error` in apps/pro-web/components/shared/markdown.tsx (look for the
MemoizedReactMarkdown usage), then run install and remove the `@ts-expect-error`
in that file if types are satisfied; also decide whether to standardize on
rehype-katex or rehype-mathjax by either removing the unused
rehype-mathjax@4.0.0 dependency or integrating it into the main
MemoizedReactMarkdown pipeline (replace rehype-katex usage or add rehype-mathjax
to the same plugins list) so math rendering is consistent across chat components
and the main markdown renderer.

Comment on lines +7 to +15
**OutlineNode** - Tree data structure representing markdown document hierarchy with stable IDs, nesting depth, and parent-child relationships. [0-cite-0](#0-cite-0)

**MarkdownSection** - Raw parsed markdown heading with embedded IDs, content boundaries, and absolute offset tracking for surgical edits. [0-cite-1](#0-cite-1)

**MessagePair** - User-assistant message grouping unit that pairs questions with responses for accordion rendering. [0-cite-2](#0-cite-2)

**Scope/ScopeId** - Section identifier (`section.id` or `node.id`) used to group messages by document sections, with special handling for root (`__doc_root__`) and orphaned messages (`__orphaned__::<scopeId>`). [0-cite-3](#0-cite-3)

**Level vs Depth** - `level` refers to markdown heading level (1-6), while `depth` refers to tree nesting depth (0+ from root). Critical distinction for styling logic. [0-cite-4](#0-cite-4)
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

All citation link fragments are broken.

Every [0-cite-N](#0-cite-N) reference resolves to a non-existent anchor. These appear throughout the entire document (lines 7, 9, 11, 13, 15, 25, 27, 29, 46, 48, 50, 54, 56, 66, 70, 72, etc.). Either define the anchor targets or replace with plain-text references.

🧰 Tools
🪛 LanguageTool

[uncategorized] ~7-~7: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...de** - Tree data structure representing markdown document hierarchy with stable IDs, nes...

(MARKDOWN_NNP)


[uncategorized] ~9-~9: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ...te-0) MarkdownSection - Raw parsed markdown heading with embedded IDs, content boun...

(MARKDOWN_NNP)


[uncategorized] ~15-~15: Did you mean the formatting language “Markdown” (= proper noun)?
Context: ... Level vs Depth - level refers to markdown heading level (1-6), while depth refe...

(MARKDOWN_NNP)

🪛 markdownlint-cli2 (0.20.0)

[warning] 7-7: Link fragments should be valid

(MD051, link-fragments)


[warning] 9-9: Link fragments should be valid

(MD051, link-fragments)


[warning] 11-11: Link fragments should be valid

(MD051, link-fragments)


[warning] 13-13: Link fragments should be valid

(MD051, link-fragments)


[warning] 15-15: Link fragments should be valid

(MD051, link-fragments)

🤖 Prompt for AI Agents
In `@Phase_0_Chat_Refactor.md` around lines 7 - 15, The document contains broken
citation link fragments like [0-cite-N](`#0-cite-N`) across multiple sections
(e.g., in definitions for OutlineNode, MarkdownSection, MessagePair,
Scope/ScopeId, and Level vs Depth); fix by either adding matching anchor targets
(e.g., create corresponding headings or anchor IDs named 0-cite-0, 0-cite-1,
etc.) or replacing each inline link with a plain-text citation (e.g., “see
citation 0-cite-0”) for the referenced concepts (OutlineNode, MarkdownSection,
MessagePair, Scope/ScopeId, Level vs Depth) so the references resolve correctly.

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