-
Notifications
You must be signed in to change notification settings - Fork 114
fix(ask_sb): Various improvements to the references system #396
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Conversation
@brendan-kellam your pull request is missing a changelog! |
WalkthroughThis update refactors and enhances the chat thread feature, focusing on reference handling, UI component modularization, and code maintainability. It introduces new components, updates reference extraction and repair logic, refines test coverage, and improves the rendering and interactivity of referenced code snippets. Several components are restructured for clarity and future extensibility. Changes
Sequence Diagram(s)sequenceDiagram
participant User
participant ChatThread
participant ChatThreadListItem
participant DetailsCard
participant ReferencedSourcesListView
participant ReferencedFileSourceListItem
User->>ChatThread: View chat thread
ChatThread->>ChatThreadListItem: Render message pair (with index)
ChatThreadListItem->>DetailsCard: Show thinking steps, details
ChatThreadListItem->>ReferencedSourcesListView: Show referenced files (with index)
ReferencedSourcesListView->>ReferencedFileSourceListItem: Render interactive code snippet
User->>ReferencedFileSourceListItem: Hover/click reference
ReferencedFileSourceListItem->>ChatThreadListItem: Update reference highlight/selection
Estimated code review effort🎯 4 (Complex) | ⏱️ ~35 minutes Suggested reviewers
Poem
Note ⚡️ Unit Test Generation is now available in beta!Learn more here, or try it out under "Finishing Touches" below. ✨ Finishing Touches
🧪 Generate unit tests
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. 🪧 TipsChatThere are 3 ways to chat with CodeRabbit:
SupportNeed help? Create a ticket on our support page for assistance with any issues or questions. Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
🧹 Nitpick comments (4)
packages/web/src/features/chat/useExtractReferences.ts (1)
9-35
: Clean refactoring that improves focus and maintainability!The simplified approach of processing a single
TextUIPart
instead of iterating over multiple message parts makes the hook more focused and easier to understand. Good use of regex reset and null safety.Consider using consistent parameter naming for better readability:
- while ((match = FILE_REFERENCE_REGEX.exec(content ?? '')) !== null && match !== null) { + while ((match = FILE_REFERENCE_REGEX.exec(content ?? '')) !== null) {The double null check is redundant since the first condition already ensures
match
is not null.packages/web/src/features/chat/components/chatThread/detailsCard.tsx (1)
121-163
: Consider adding error boundaries and accessibility improvements.The switch statement handles the main tool types well, but consider these enhancements:
- Add error boundary for tool component failures
- Improve accessibility with ARIA labels
- Consider logging unhandled part types for debugging
default: + console.warn('Unhandled part type:', part.type); return null;
Also consider adding
aria-label
to the collapsible trigger for better screen reader support.packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx (1)
162-173
: Consider a more robust approach for state synchronization.While
requestAnimationFrame
works, it's a timing-based solution that might be fragile. Consider using auseEffect
hook that watches for changes incollapsedFileIds
to trigger the scroll, or use a callback ref pattern to ensure the DOM is updated before scrolling.- // Expand the file if it's collapsed. - setCollapsedFileIds((collapsedFileIds) => collapsedFileIds.filter((id) => id !== fileId)); - - // Scroll to the calculated position - // @NOTE: Using requestAnimationFrame is a bit of a hack to ensure - // that the collapsed file ids state has updated before scrolling. - requestAnimationFrame(() => { - scrollAreaViewport.scrollTo({ - top: Math.max(0, targetScrollTop), - behavior: 'smooth', - }); - }); + // Expand the file if it's collapsed. + const wasCollapsed = collapsedFileIds.includes(fileId); + if (wasCollapsed) { + setCollapsedFileIds((prev) => prev.filter((id) => id !== fileId)); + } + + // Scroll to the calculated position + // If the file was collapsed, delay scrolling to next tick + const scrollToTarget = () => { + scrollAreaViewport.scrollTo({ + top: Math.max(0, targetScrollTop), + behavior: 'smooth', + }); + }; + + if (wasCollapsed) { + requestAnimationFrame(scrollToTarget); + } else { + scrollToTarget(); + }packages/web/src/features/chat/components/chatThread/chatThreadListItem.tsx (1)
389-403
: Consider memoizing the nearest reference calculation.The
getNearestReferenceElement
function performs DOM measurements which can be expensive. If this is called frequently (e.g., during scrolling), consider memoizing the result or debouncing the calls.+import { memoize } from 'lodash'; + // Finds the nearest reference element to the viewport center. -const getNearestReferenceElement = (referenceElements: Element[]) => { +const getNearestReferenceElement = memoize((referenceElements: Element[]) => { return referenceElements.reduce((nearest, current) => { // ... existing logic ... }); -} +}, (elements) => elements.map(el => el.className).join(','));
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (14)
packages/web/src/features/chat/components/chatThread/chatThread.tsx
(1 hunks)packages/web/src/features/chat/components/chatThread/chatThreadListItem.tsx
(7 hunks)packages/web/src/features/chat/components/chatThread/codeFoldingExtension.test.ts
(1 hunks)packages/web/src/features/chat/components/chatThread/codeFoldingExtension.ts
(1 hunks)packages/web/src/features/chat/components/chatThread/detailsCard.tsx
(1 hunks)packages/web/src/features/chat/components/chatThread/markdownRenderer.tsx
(1 hunks)packages/web/src/features/chat/components/chatThread/referencedFileSourceListItem.tsx
(1 hunks)packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx
(8 hunks)packages/web/src/features/chat/constants.ts
(2 hunks)packages/web/src/features/chat/tools.ts
(1 hunks)packages/web/src/features/chat/useExtractReferences.test.ts
(1 hunks)packages/web/src/features/chat/useExtractReferences.ts
(1 hunks)packages/web/src/features/chat/utils.test.ts
(2 hunks)packages/web/src/features/chat/utils.ts
(4 hunks)
🧰 Additional context used
📓 Path-based instructions (1)
**/*
📄 CodeRabbit Inference Engine (.cursor/rules/style.mdc)
Filenames should always be camelCase. Exception: if there are filenames in the same directory with a format other than camelCase, use that format to keep things consistent.
Files:
packages/web/src/features/chat/components/chatThread/markdownRenderer.tsx
packages/web/src/features/chat/components/chatThread/chatThread.tsx
packages/web/src/features/chat/components/chatThread/codeFoldingExtension.ts
packages/web/src/features/chat/tools.ts
packages/web/src/features/chat/constants.ts
packages/web/src/features/chat/components/chatThread/codeFoldingExtension.test.ts
packages/web/src/features/chat/utils.test.ts
packages/web/src/features/chat/useExtractReferences.ts
packages/web/src/features/chat/useExtractReferences.test.ts
packages/web/src/features/chat/components/chatThread/detailsCard.tsx
packages/web/src/features/chat/components/chatThread/referencedFileSourceListItem.tsx
packages/web/src/features/chat/components/chatThread/chatThreadListItem.tsx
packages/web/src/features/chat/utils.ts
packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build
🔇 Additional comments (22)
packages/web/src/features/chat/components/chatThread/codeFoldingExtension.ts (1)
345-346
: Good practice: Sorting decorations by positionThis sorting ensures proper ordering of decorations for CodeMirror, which is essential for efficient rendering and interaction with multiple folded regions.
packages/web/src/features/chat/constants.ts (2)
1-1
: Proper import for type safetyGood addition of the import for proper typing of the new constant.
19-27
: Well-structured constant for UI visibility controlThis centralized constant improves maintainability by defining which message part types are visible in the UI. The proper typing with
SBChatMessagePart['type'][]
andas const
ensures type safety and literal type inference.packages/web/src/features/chat/components/chatThread/chatThread.tsx (1)
272-272
: Good addition: Index prop for enhanced reference handlingAdding the index prop provides positional context to ChatThreadListItem components, supporting the enhanced reference handling and UI behavior improvements mentioned in the PR objectives.
packages/web/src/features/chat/components/chatThread/codeFoldingExtension.test.ts (1)
485-486
: Good fix: Added missing repo property for test consistencyThis addition ensures the FileReference object in this test case matches the structure used in other test cases, maintaining consistency in test data.
packages/web/src/features/chat/components/chatThread/markdownRenderer.tsx (1)
66-71
: Excellent change: Using class instead of id for reference elementsThis is a semantically correct improvement. HTML
id
attributes must be unique within a document, but multiple reference elements may point to the same file and range. Usingclass
is the appropriate approach here and supports the enhanced reference highlighting functionality. The added comments clearly explain the reasoning.packages/web/src/features/chat/tools.ts (1)
12-21
: Excellent documentation for tool extension process!This comprehensive guide clearly outlines all the necessary steps for adding new tools, including file updates and UI integration points. This will significantly improve developer experience and maintain consistency across tool implementations.
packages/web/src/features/chat/useExtractReferences.test.ts (1)
7-40
: Test update aligns perfectly with the hook refactoring!The simplified test structure using
TextUIPart
directly is cleaner and more focused. Good coverage with both file-only and file-with-range reference scenarios.packages/web/src/features/chat/utils.test.ts (2)
246-329
: Comprehensive test coverage for the renamed function!All existing test cases properly updated to use
repairReferences
instead ofrepairCitations
. The test coverage is thorough, covering various malformed reference scenarios and edge cases.
331-353
: Excellent addition of edge case tests!The new test cases effectively cover additional repair scenarios:
- Extra closing parenthesis handling
- Extra colon removal at range end
- Inline code block stripping (both well-formed and malformed)
These edge cases are realistic and improve the robustness of the reference repair functionality.
packages/web/src/features/chat/components/chatThread/detailsCard.tsx (4)
17-24
: Well-designed props interface!The interface clearly defines all necessary props with appropriate types. Good separation of concerns with boolean flags for state and proper typing for complex data structures.
48-60
: Good conditional rendering for thinking state!The dynamic header that shows either "Thinking..." with spinner or "Details" with info icon provides clear visual feedback to users about the current state.
61-87
: Comprehensive metadata display with good UX!The metadata section provides valuable information (model, tokens, timing, step count) with appropriate icons. The conditional rendering based on streaming state prevents showing incomplete data.
106-120
: Well-implemented step numbering with visual hierarchy!The numbered bullets with vertical borders create a clear visual progression through the thinking steps. Good use of absolute positioning for the step numbers.
packages/web/src/features/chat/utils.ts (3)
244-262
: LGTM! Good improvements to the markdown conversion.The changes properly clean up the input by removing the answer tag and trimming whitespace. The file reference conversion to markdown links is well-implemented.
294-312
: Well-structured enhancements to reference repair logic.The additional regex patterns effectively handle more edge cases of malformed references. The sequential application of fixes is appropriate and covers common LLM output mistakes.
316-328
: Good separation of concerns.The removal of
repairReferences
from this function appropriately delegates the repair logic to the component level, making the function more focused on its primary responsibility of extracting the answer part.packages/web/src/features/chat/components/chatThread/referencedFileSourceListItem.tsx (2)
190-198
: Potential edge case in mouseout handler.The mouseout handler returns
false
when still over a reference (line 193), which prevents the default handling. This might cause issues if the mouse moves directly from one reference to another without triggering a mouseout event, potentially leaving the hover state stuck.Consider tracking the previously hovered reference and explicitly clearing it when hovering over a different reference.
276-327
: Well-structured component with good separation of concerns.The component effectively encapsulates the code display functionality with interactive reference highlighting. The conditional rendering and state management are properly implemented.
packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx (1)
236-278
: Excellent refactoring with improved modularity.The delegation of file source rendering to
ReferencedFileSourceListItem
significantly improves code organization. The collapse/expand logic with scroll restoration provides a good user experience.packages/web/src/features/chat/components/chatThread/chatThreadListItem.tsx (2)
49-73
: Well-implemented reference repair with proper immutability.The logic correctly applies repairs only to text-based parts while maintaining type safety with the
satisfies
operator. Good defensive programming with the optional chaining.
321-328
: Clean component composition with proper prop passing.The integration of
DetailsCard
and the addition of theindex
prop toReferencedSourcesListView
are well-implemented. The component maintains good separation of concerns.Also applies to: 359-359
…urce. Added posthog event and audit log for goto/find all refs for chat
There was a problem hiding this 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)
packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx (2)
162-173
: LGTM! Auto-expansion improves user experience.The logic to automatically expand collapsed files when scrolling to selected references is a good UX improvement. The
requestAnimationFrame
approach, while a bit hacky as noted, is a pragmatic solution to ensure state updates before scrolling.Consider using a
useLayoutEffect
oruseEffect
with proper dependency management as an alternative torequestAnimationFrame
for more predictable timing:- // @NOTE: Using requestAnimationFrame is a bit of a hack to ensure - // that the collapsed file ids state has updated before scrolling. - requestAnimationFrame(() => { - scrollAreaViewport.scrollTo({ - top: Math.max(0, targetScrollTop), - behavior: 'smooth', - }); - }); + scrollAreaViewport.scrollTo({ + top: Math.max(0, targetScrollTop), + behavior: 'smooth', + });And handle the timing through a separate effect that watches
collapsedFileIds
.
236-276
: LGTM! Well-structured component delegation with good UX considerations.The refactoring to use
ReferencedFileSourceListItem
effectively separates concerns and delegates CodeMirror complexity to a specialized component. The expansion/collapse logic includes thoughtful UX improvements like auto-scrolling to the file header when collapsing.Consider extracting the complex
onExpandedChanged
callback to a separateuseCallback
for better readability:const handleExpandedChanged = useCallback((fileId: string, isExpanded: boolean) => { if (isExpanded) { setCollapsedFileIds(collapsedFileIds.filter((id) => id !== fileId)); } else { setCollapsedFileIds([...collapsedFileIds, fileId]); } // Scroll to top when collapsing for better UX if (!isExpanded) { const fileSourceStart = document.getElementById(`${fileId}-start`); if (fileSourceStart) { scrollIntoView(fileSourceStart, { scrollMode: 'if-needed', block: 'start', behavior: 'instant', }); } } }, [collapsedFileIds]);
📜 Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro
⛔ Files ignored due to path filters (1)
yarn.lock
is excluded by!**/yarn.lock
,!**/*.lock
📒 Files selected for processing (5)
packages/web/package.json
(2 hunks)packages/web/src/features/chat/components/chatThread/referencedFileSourceListItem.tsx
(1 hunks)packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx
(7 hunks)packages/web/src/features/search/fileSourceApi.ts
(1 hunks)packages/web/src/features/search/schemas.ts
(1 hunks)
✅ Files skipped from review due to trivial changes (3)
- packages/web/src/features/search/fileSourceApi.ts
- packages/web/package.json
- packages/web/src/features/search/schemas.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/web/src/features/chat/components/chatThread/referencedFileSourceListItem.tsx
🧰 Additional context used
📓 Path-based instructions (1)
**/*
📄 CodeRabbit Inference Engine (.cursor/rules/style.mdc)
Filenames should always be camelCase. Exception: if there are filenames in the same directory with a format other than camelCase, use that format to keep things consistent.
Files:
packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
- GitHub Check: build
🔇 Additional comments (8)
packages/web/src/features/chat/components/chatThread/referencedSourcesListView.tsx (8)
8-8
: LGTM! Import changes support the refactoring.The added imports align well with the component refactoring - service error utilities for better error handling, additional React hooks for expanded state management, and the new
ReferencedFileSourceListItem
component for delegated CodeMirror logic.Also applies to: 10-11, 14-14
19-19
: LGTM! Index prop enables unique file ID generation.The
index
prop is appropriately added to ensure unique file IDs across multipleReferencedSourcesListView
instances within the same thread.
37-37
: LGTM! Props destructuring updated correctly.The
index
prop is properly destructured to match the updated interface.
47-47
: LGTM! External state management improves component architecture.Moving the collapsed file state to the parent component provides better control over expansion state and aligns with the refactoring to delegate CodeMirror logic to child components.
49-54
: LGTM! Unique file ID generation with clear reasoning.The
getFileId
function correctly incorporates theindex
parameter to ensure uniqueness across multiple component instances. The detailed comment explains the rationale clearly.
97-97
: LGTM! Dependencies array correctly updated.Adding
getFileId
to the dependencies array is necessary since the function now depends on theindex
prop and could change between renders.
184-184
: LGTM! useEffect dependencies correctly updated.Adding
getFileId
to the dependencies array is necessary since the function is used within the effect and now depends on theindex
prop.
30-30
: Potential false positives with suffix matchingSwitching from strict equality to
endsWith(reference.path)
can unintentionally match multiple files if two or moreFileSource.path
values share the same ending (for example, “index.ts”). Please verify that:
- Every
reference.path
value includes enough of the directory structure (or is unique) so that its suffix alone can’t collide with other files.- No two
FileSource.path
entries end with an identical substring that could lead to selecting the wrong source.If suffixes aren’t guaranteed unique, consider one of the following:
- Revert to exact
source.path === reference.path
comparison.- Normalize and compare full paths (e.g., absolute or root-relative).
- Introduce a more precise matching strategy (e.g., comparing both prefix and suffix).
Improvements:
Summary by CodeRabbit
New Features
Improvements
Bug Fixes
Documentation
Tests
Refactor